[LeetCode] 186. Reverse Words in a String II

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

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

Follow up: Could you do it in-place without allocating extra space?

翻转字符串里的单词II。题意是给一个用char array的句子,请翻转单词的顺序。

思路是先翻转整个input数组,然后用快慢指针扫描input,快指针在空格的地方停下,翻转快慢指针之间的字符。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public void reverseWords(char[] s) {
 3         reverse(s, 0, s.length - 1);
 4         int r = 0;
 5         while (r < s.length) {
 6             int l = r;
 7             while (r < s.length && s[r] != ' ') {
 8                 r++;
 9             }
10             reverse(s, l, r - 1);
11             r++;
12         }
13     }
14 
15     private void reverse(char[] s, int i, int j) {
16         while (i < j) {
17             char temp = s[i];
18             s[i] = s[j];
19             s[j] = temp;
20             i++;
21             j--;
22         }
23     }
24 }

 

JavaScript实现

 1 /**
 2  * @param {character[]} s
 3  * @return {void} Do not return anything, modify s in-place instead.
 4  */
 5 var reverseWords = function (s) {
 6     helper(s, 0, s.length - 1);
 7     let r = 0;
 8     while (r < s.length) {
 9         let l = r;
10         while (r < s.length && s[r] != ' ') {
11             r++;
12         }
13         helper(s, l, r - 1);
14         r++;
15     }
16 };
17 
18 var helper = function (s, i, j) {
19     while (i < j) {
20         let temp = s[i];
21         s[i] = s[j];
22         s[j] = temp;
23         i++;
24         j--;
25     }
26 }

 

相关题目

151. Reverse Words in a String

186. Reverse Words in a String II

344. Reverse String

541. Reverse String II

557. Reverse Words in a String III

LeetCode 题目总结

posted @ 2020-03-24 06:50  CNoodle  阅读(215)  评论(0编辑  收藏  举报