Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
class Solution{
public:
void reverseWords(string &s){
string str;
stack<char> st;
for(char i:s){
if(i==‘ ‘){
while(!st.empty()){
str+=st.top();
st.pop();
if(st.empty())str+=" ";//去除中间多余的空格
}
}
else st.push(i);
}
while(!st.empty()){
str+=st.top();
st.pop();
}
//去除前后空格
while(!str.empty()&&str[0]==‘ ‘)str.erase(str.begin());
while(!str.empty()&&str.length()>=1&&str[str.length()-1]==‘ ‘)str.erase(str.end()-1);
reverse(str.begin(),str.end());
s.assign(str);
}
};LeetCode OJ:Reverse Words in a String,布布扣,bubuko.com
LeetCode OJ:Reverse Words in a String
原文:http://blog.csdn.net/starcuan/article/details/21020455