[Leetcode] Reverse Words in a String
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] = '\0'; 34 len--; 35 } 36 s.resize(len); 37 } 38 39 void reverseWords(string &s) { 40 removeBlank(s); 41 reverse(s,0,s.length()-1); 42 int a = 0, b; 43 for (int i=0; i<=s.length();++i){ 44 if(s[i]==' '||s[i]=='\0'){ 45 b = i-1; 46 reverse(s,a,b); 47 a = i+1; 48 } 49 } 50 return; 51 } 52 };