151. Reverse Words in a String
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
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.
Follow up: For C programmers, try to solve it in-place in O(1) space.
思路
这个是老题目了,字符串倒序,最简单的方法是先字符串整体翻转一次,然后每个单词再翻转一次即可。
这里不想用这种方法,迷上了使用istringstream来处理这种string类型的题目。
- 以空格
' '
为分隔符进行分割 - 如果有多个空格连在一起,那么分隔到的字符串为空,跳过即可
- 将分割后的字符串倒序串接即可
代码
class Solution {
public:
void reverseWords(string &s) {
istringstream iss(s);
string tmp = "";
s = "";
while (getline(iss, tmp, ' ')) {
if (tmp.empty()) continue;
s = s.empty() ? tmp : (tmp + " " + s);
}
}
};