原题描述:
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> v;
string ch = "";
for (string::size_type i = 0; i < s.size(); i++) {
if (s[i] == ' ' && ch != "") {
v.push(ch);
ch = "";
}
while (i < s.size() && s[i] == ' ') i++;
if (i < s.size()) ch += s[i];
}
if (ch != "") v.push(ch);
s = "";
while (!v.empty()) {
s += v.top();
v.pop();
if (!v.empty()) s += " ";
}
}
};
特殊情况描述如下:
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
主要就是考虑:开头、中间、结尾 有很多个空格,以及结尾没有空格的情况。