Reverse Words In String
Given an input string, reverse the string word by word.
For example, Given s = "the sky is blue", return "blue is sky the".
Solution: Double Reverse
- Reverse the individual words, we get the below string.
- Reverse the whole string from start to end and you get the desired output.
Note: If we need to trim the space at the start and end of the string, using stack is a better solution
Solution: Using stack
- Traverse the string and push each word
- Pop each word and append it to the new string.
void reverseWords(string &s) {
stack<string> m;
string word = "";
for (auto ch: s) {
if (ch != ' ') {
word += ch;
} else if (!word.empty()) {
m.push(word);
word = "";
}
}
if (!word.empty()) m.push(word);
s = "";
while(!m.empty()) {
s += m.top();
m.pop();
s += m.empty() ? "" : " ";
}
}