您的位置:首页 > 其它

[Leetcode]151. Reverse Words in a String

2016-08-13 11:37 393 查看
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) {
if (s.size() == 0)
return;
string result = "";
if (s[s.size() - 1] == ' ') {
int last = s.find_last_not_of(' ') + 1;
s.erase(last, s.size() - last);
}
int first = s.find_first_not_of(' ', 0);
while (first != string::npos) {
int last = s.find(' ', first);
if (last == string::npos)
last = s.size();

string word = s.substr(first, last - first);
reverse(word.begin(), word.end());
result += word;

first = s.find_first_not_of(' ', last);
if (first == string::npos)
break;
result += ' ';
}
reverse(result.begin(), result.end());
s.swap(result);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode