186. Reverse Words in a String II π
DifficultyMedium
Description
Given a character array s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.
Your code must solve the problem in-place, i.e. without allocating extra space.
Example 1:
Input: s = ["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"]
Example 2:
Input: s = ["a"] Output: ["a"]
Constraints:
1 <= s.length <= 105s[i]is an English letter (uppercase or lowercase), digit, or space' '.- There is at least one word in
s. sdoes not contain leading or trailing spaces.- All the words in
sare guaranteed to be separated by a single space.
Solutions
Solution 1: Two Pointers
Thinking
Reverse the word order in a character array in place; words are separated by a single space. \(n\le 10^5\), \(O(1)\) extra space. Reverse each word, then reverse the whole array: word order flips and letters inside a word return to normal. Two pointers mark each word.
We can iterate through the character array \(s\), using two pointers \(i\) and \(j\) to find the start and end positions of each word, then reverse each word, and finally reverse the entire character array.
The time complexity is \(O(n)\), where \(n\) is the length of the character array \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |