您的位置:首页 > 其它

【leetcode刷题笔记】Reverse Words in a String

2014-04-28 16:35 225 查看
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) {
stack<string>st;
string temp = "";

for(int i = 0;i <= s.length();i++){
if(i == s.length())
{
st.push(temp);
}
else if(s[i] != ' '){
temp += s[i];
}
else
{
if(temp != ""){
st.push(temp);
temp = "";
}
}
}
s = "";
while(!st.empty()){
if(st.top() != " ")
s += st.top();
st.pop();
if(!st.empty() && s != ""){
s += " ";
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: