您的位置:首页 > 其它

leetcode Reverse Words in a String

2015-12-09 20:04 387 查看
原题链接:https://leetcode.com/problems/reverse-words-in-a-string/

Description

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) {
n = s.length();
string x = "";
reverse(s.begin(), s.end());
while (!op.empty()) op.pop();
for (size_t i = 0; i < n;) {
while (i < n && s[i] == ' ') i++;
if (i == n) break;
while (i < n && s[i] != ' ') { op.push(s[i++]); }
while (!op.empty()) { x += op.top(); op.pop(); }
x += ' ';
}
if (x.length()) x.pop_back();
s = x;
}
private:
size_t n;
stack<char> op;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: