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.
click to show clarification.
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.
Solution
Two pointers
思路還是很清晰的,先翻轉每個word,再翻轉整個String。
有坑的地方是:
- 開頭和結尾的space要移除掉。
- word之間要保留一個space。這個可以邊遍歷邊對words進行計數,遇到新單詞且之前已經有單詞才插入space。
public class Solution {
public static void main(String[] args) {
final String input = " ab c dec ";
System.out.println("[" + new Solution().reverseWords(input) + "]");
}
public String reverseWords(String s) {
if (s == null || s.isEmpty()) {
return s;
}
char[] chars = s.toCharArray();
int len = compressWords(chars);
reverseStr(chars, 0, len - 1);
return String.valueOf(chars, 0, len);
}
public int compressWords(char[] chars) {
int i = 0;
int j = 0;
int wordsCount = 0;
while (i < chars.length) {
// escape spaces and find the beginning of a new word
while (i < chars.length && chars[i] == ' ') {
++i;
}
if (i == chars.length) break;
if (wordsCount > 0) {
chars[j++] = ' '; // leave a space in between of words
}
int k = j;
// find the ending of the word
while (i < chars.length && chars[i] != ' ') {
chars[j++] = chars[i++];
}
reverseStr(chars, k, j - 1);
++wordsCount;
}
return (j > 0 && chars[j - 1] == ' ') ? j - 1 : j; // remove the trailing space if any
}
public void reverseStr(char[] chars, int start, int end) {
while (start < end) {
char tmp = chars[start];
chars[start++] = chars[end];
chars[end--] = tmp;
}
}
}