Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue
" Output: "blue is sky the
"
Example 2:
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
思路:
我们将字符串中的每个字单独存下来,然后在依次反向输出即可。
class Solution {
public:
string reverseWords(string s) {
vector<string> tmp;
string word;
s += ' ';
for (auto i : s) {
if (isspace(i)) {
if (!word.empty()) tmp.push_back(word);
word = "";
}
else {
word += i;
}
}
if (tmp.empty()) return word;
string res;
for (auto it = tmp.end() - 1; it != tmp.begin(); it--) {
res += *it + ' ';
}
res += tmp.front();
return res;
}
};