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


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
欢迎关注我个人公众号:「一个不甘平凡的码农」,记录了自己一路自学编程的故事。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值