LeetCode 之 JavaScript 解答第151题 —— 反转字符串中的单词 (Reverse Words in a String)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36903042/article/details/89455501

Time:2019/4/20
Title: Reverse Words In a String
Difficulty: Midumn
Author: 小鹿


题目:Reverse Words In a String(翻转字符串里的单词)

Given an input string, reverse the string word by word.

给定一个字符串,逐个翻转字符串中的每个单词。

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

Solve:

▉ 问题分析

所有的单词进行倒序输出,且单词之间的空格只需保留一个,句子前后的空格全部清除。通过题目具体要求,我们已经对问题分析清除,只要解决怎么消除句子前后空格,以及倒序拼接单词,将单词之间的空格数减少至一就可以完成此题作答。

▉ 算法思路

1)跳过句子前所有空格。

2)借助变量反转单词,每遍历到一个字符,在遇到下一个空格之前,为一个完整单词。

3)遇到空格之后,将单词进行倒序拼接。

4)消除尾部的空格。

▉ 测试用例

1)空字符串。

2)中间空格大于 1 的字符串。

3)单词中有标点符号的字符串。

▉ 代码实现
 var reverseWords = function(s) {
     // 判断当前的单词是否为空字符串
     if(s.length === 0) return "";

     let [index,len] = [0,s.length];
     let word = "";
     let result = "";

     while(index < len){
         // 跳过空格
         while(index < len && s.charAt(index) == ' '){
             index ++;
         }

         // 反转单词
         while(index < len && s.charAt(index) !== ' '){
             word = `${word}${s.charAt(index)}`;
             index ++;
         }
         // 拼接
         result = word + ' ' + result;
         word = "";
     }
     return result.trim(); 
 };

欢迎一起加入到 LeetCode 开源 Github 仓库,可以向 me 提交您其他语言的代码。在仓库上坚持和小伙伴们一起打卡,共同完善我们的开源小仓库!
Github:https://github.com/luxiangqiang/JS-LeetCode

欢迎关注我个人公众号:「一个不甘平凡的码农」,记录了自己一路自学编程的故事。

猜你喜欢

转载自blog.csdn.net/qq_36903042/article/details/89455501