您的位置:首页 > 其它

151.leetcode Reverse Words in a String(medium)[字符串分词翻转]

2016-08-24 19:49 711 查看
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) {
int n = s.size();
if(n<1) return;
stack<string> words;
string temp = "";
for(int i=0;i<n;i++)
{
if(s[i] != ' ')
temp += s[i];
else
{
if(temp != "")
{ words.push(temp);
temp = "";
}
}
}
if(temp != "")
{
words.push(temp);
}
s = "";
while(!words.empty())
{
s += words.top()+" ";
words.pop();
}
s = s.substr(0,s.size()-1);
return;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: