Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
思路:in-place方法。
先将字符串s反转,去除多余的空格,然后把每个单词再反转一次。
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 int l = 0, r = s.size() - 1; 5 while (l < r) 6 swap(s[l++], s[r--]); 7 for (int i = 0; i < s.size(); i++) 8 { 9 if (i == 0) 10 while (i < s.size() && s[i] == ' ')//eliminate spaces at the beginning 11 s.erase(s.begin()); 12 else if (s[i - 1] == ' ') 13 while (i < s.size() && s[i] == ' ')//eliminate duplicate spaces in the string 14 s.erase(s.begin() + i); 15 } 16 while (s.back() == ' ')//eliminate spaces at the end of the string 17 s.erase(s.end() - 1); 18 for (int i = 0, n = s.size(); i < n;) 19 { 20 for (r = i + 1; r < n && s[r] != ' '; r++);//find the last character of the current word 21 l = i, r--;//reverse the current word 22 i = r + 2; 23 while (l < r) 24 swap(s[l++], s[r--]); 25 } 26 } 27 };