Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
反转字符串中单词的顺序。有3中可能的情况(用_表示空格):
1. a_b
2. __
3. _ab
4. ab_
第一种情况也是最普遍的情况,检测空格并反转字符串中单词即可。
第二、三、四种情况需要消除由1反转后多余空格。思路是将二、三种情况都转化为第四种,利用一个变量计数来统计非空格的字符数量,使用substr将最后一个空格消去
class Solution { public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int tmp = 0; for (int i = 0; i != s.size(); i++) { if (s[i] == ' ') { reverse(s.begin() + tmp, s.begin() + i); tmp = i + 1; } } reverse(s.begin() + tmp, s.end()); int t = 0; for (int i = 0; i != s.size(); i++) { if (s[i] != ' ') { s[t++] = s[i]; if (s[i + 1] == ' ' || i == s.size() - 1) s[t++] = ' '; } } s = s.substr(0, t == 0 ? 0 : t - 1); } }; // 6 ms