Description:
Given an input string, reverse the string word by word.
For example,
Given S ="the sky is blue",
Return"blue is sky the".
Solution:
The solution to this problem is simple. Create a New String, traverse the given string from the back to the front, and add a word to the new string. Do not forget to add a space. Of course, the white space at the beginning and end of a given string must be removed in advance. The code for this question is as follows:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 int i = 0; 5 int j = s.size() - 1; 6 string str; 7 for(; s[i] == ‘ ‘; ++i); 8 for(; s[j] == ‘ ‘; --j); 9 10 int temp;11 for(temp = j; temp >= i; --temp){12 if (s[temp] == ‘ ‘ && s[temp + 1] != ‘ ‘){13 str.append(s, temp + 1, j - temp);14 str.append(1, ‘ ‘);15 }16 if (s[temp] != ‘ ‘ && s[temp + 1] == ‘ ‘) {17 j = temp;18 }19 }20 str.append(s, temp + 1, j - temp);21 s = str;22 }23 };
Reverse words in a string