Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue", Output: "blue is sky the".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
题目链接:https://leetcode.com/problems/reverse-words-in-a-string/
class Solution {
public:
void reverseWords(string &s) {
int n=s.size();
string str="";
stack<string> stk;
for(int i=0;i<n;)
{
if(s[i]!=' ')
{
str+=s[i];
i++;
}
else{
if(str.size()>0)
stk.push(str);
str="";
while(s[i]==' ')
{
i++;
}
}
}
if(str.size()>0)
stk.push(str);
s="";
while(!stk.empty())
{
s+=stk.top();
stk.pop();
if(!stk.empty())
s+=" ";
}
}
};