LeetCode 之 JavaScript 解答第151题 —— 反转字符串中的单词

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/luxiangqia…

迎接关注我个人民众号:「一个不甘寻常的码农」,记录了本身一起自学编程的故事。

    原文作者:小鹿
    原文地址: https://segmentfault.com/a/1190000018949482
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞