Question:
Given an input string, reverse the string word by word.
For example,
Given S ="the sky is blue",
Return"blue is sky the".
Train of Thought: Method 1: first, the sentence is regarded as composed of words, such as "a B C". Therefore, all the characters in the sentence can be exchanged before and after, obtain "C 'B '". Obviously, x' indicates the reverse word X, so the second step is to swap the strings in each word before and after. The time complexity of the entire process is O (n), and the space complexity is O (1 ). The disadvantage of this method is that many special cases are not taken into account, such as consecutive spaces in the string and spaces at the start and end of the string.
Method 2: Use two stacks, one representing a word and one representing a sentence. When a non-space character is encountered, place it in the word stack. When a space character is encountered, press the character in the word stack into the sentence stack (Note: The word has already been in reverse order), and then add only one space. Finally, the sentence stack is output in sequence. At this time, the sentence is in reverse order. The two reverse order principles are the same as the method 1.
Code: Method 1:
class Solution {public: void reverseWords(string &s) { int begin = 0; int end = 0; while(end < s.size()){ if(s[end] == ' '){ swapString(s, begin, end - 1); begin = end+1; end = begin; } else{ end++; } } swapString(s, begin, end - 1); swapString(s, 0, s.size()-1); } void swapString(string &s, int begin, int end){ while(end > begin){ char c = s[begin]; s[begin] = s[end]; s[end] = c; begin++; end--; } }};
Method 2:
class Solution {public: void reverseWords(string &s) { stack<int> word; stack<int> sentence; int i = 0; while(i <= s.size()){ if(i == s.size() || s[i] == ' '){ if(!word.empty()){ if(!sentence.empty()){ sentence.push(' '); } while(!word.empty()){ sentence.push(word.top()); word.pop(); } } } else{ word.push(s[i]); } i++; }; s.clear(); while(!sentence.empty()){ s.push_back(sentence.top()); sentence.pop(); }; }};
Leetcode | reverse words in a string