Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
没什么多说的,去空格看似挺麻烦,一次遍历就能搞定。注意最后的空格要特殊处理。
1 class Solution { 2 public: 3 void reverse(string &s, int low, int high) { 4 char tmp; 5 while(low < high) { 6 tmp = s[low]; 7 s[low] = s[high]; 8 s[high] = tmp; 9 low++; 10 high--; 11 } 12 } 13 14 void removeBlank(string &s) { 15 if (s.length() == 0) { 16 return; 17 } 18 int count = 0; 19 bool flag = false; 20 for (int i = 0; i <= s.length(); ++i) { 21 if (s[i] == ' ' && !flag) { 22 count++; 23 } else if (s[i] == ' ' && flag) { 24 flag = false; 25 s[i-count] = s[i]; 26 } else if (s[i] != ' ') { 27 flag = true; 28 s[i-count] = s[i]; 29 } 30 } 31 int len = s.length() - count; 32 if (s[len-1] == ' ') { 33 s[len-1] = '