Question:
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. cocould the input string contain leading or trailing spaces?
Yes. However, your reversed string shocould not contain leading or trailing spaces. How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Solution:
Extract each word from start to end, and assign a value in reverse order. Because the stack is "advanced and later", I use the stack implementation.
class Solution {public: void reverseWords(string &s) { stack
stk; istringstream in(s); string tmp; while( in >> tmp) stk.push(tmp); s = ""; while(!stk.empty()) { s +=stk.top(); if(stk.size()!=1) s +=" "; stk.pop(); } }};