Reverse Words in a String 151
Description
Given an input string, reverse the string word by word.
For example, Given s = "the sky is blue", return "blue is sky the".
Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words? Reduce them to a single space in the reversed string.
Hint
reverse and reverse again
Method
reverse all chars in string then reverse each word's chars
Time & Space
o(n)
Code
public class Solution {
public String reverseWords(String s) {
if (s == null){
return s;
}
char[] strs = s.toCharArray();
reverse(strs, 0, s.length() - 1);
int i = 0, j = 0;
while (i < s.length()){
while (i < j || i < s.length() && strs[i] == ' '){
i++;
}
while (j < i || j < s.length() && strs[j] != ' '){
j++;
}
reverse(strs, i, j - 1);
}
i = 0;
j = 0;
while (j < s.length()){
while (j < s.length() && strs[j] == ' '){
j++;
}
while (j < s.length() && strs[j] != ' '){
strs[i++] = strs[j++];
}
while (j < s.length() && strs[j] == ' '){
j++;
}
if (j < s.length()){
strs[i++] = ' ';
}
}
return new String(strs).substring(0, i);
}
public void reverse(char[] strs, int start, int end){
while (start < end){
char c = strs[start];
strs[start] = strs[end];
strs[end] = c;
start++;
end--;
}
}
}