[LeetCode] 186. Reverse Words in a String II

Flip words in strings II. Meaning of the questions is to use a char array sentences, please flip the order of words. example,

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"]

The idea is to flip an entire input array, and then use the pointer speed scanning input, fast pointer in place of a space to stop, flipped the characters between the speed of the pointer.

Time O (n)

Space O (n)

Java implementation

 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 implementation

 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 }

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12556582.html