标签:
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.
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 if (s.empty()) return; 5 reverse(s.begin(), s.end()); 6 7 int left = 0, right = 0, wordBegin = 0; 8 int index = 0; 9 for (; index < s.size(); index++) { 10 if (isspace(s[index])) continue; 11 if (index == 0 || isspace(s[index - 1])) 12 left = index; 13 if (index == s.size() - 1 || isspace(s[index + 1])) right = index; 14 else continue; 15 16 reverse(s.begin() + left, s.begin() + right + 1); 17 // leading 0s before the word 18 if (wordBegin < left) { 19 while (left <= right) { 20 s[wordBegin++] = s[left++]; 21 } 22 s[wordBegin] = ‘ ‘; 23 wordBegin++; 24 } else { 25 wordBegin = right + 2; 26 } 27 } 28 wordBegin = wordBegin ? wordBegin : 1; 29 s.erase(s.begin() + wordBegin - 1, s.end()); 30 } 31 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/5902327.html