Description
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?
Solution
Two-pass iteration, time O(n), space O(1)
很常见的两遍reverse解法。
class Solution {
public void reverseWords(char[] str) {
if (str == null) {
return;
}
int i = 0;
int len = str.length;
while (i < len) {
int j = i + 1;
while (j < len && str[j] != ' ') {
++j;
}
reverse(str, i, j - 1);
i = j + 1;
}
reverse(str, 0, len - 1);
}
public void reverse(char[] arr, int left, int right) {
while (left < right) {
swap(arr, left++, right--);
}
}
public void swap(char[] arr, int i, int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}