186. Reverse Words in a String II
Last updated
Last updated
/**
* Time complexity : O(N), it's two passes along the string.
* Space complexity : O(1), it's a constant space solution.
*/
class Solution {
public void reverseWords(char[] s) {
if(s == null || s.length == 0) return;
// reverse the whole string
reverse(s, 0, s.length-1);
// reverse each word
reverseEachWord(s);
}
private void reverse(char[] chars, int left, int right) {
while(left < right) {
char tmp = chars[left];
chars[left++] = chars[right];
chars[right--] = tmp;
}
}
private void reverseEachWord(char[] chars) {
int n = chars.length;
int start = 0, end = 0;
while(start < n) {
// go to the end of the word
while(end < n && chars[end] != ' ') {
end++;
}
// reverse the word
reverse(chars, start, end-1);
// move to the next word
end++;
start = end;
}
}
}