leetcode summary-section II
151 Reverse Words in a String
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 string result; 5 for (int i = s.size() - 1; i >= 0;) { 6 while (i >= 0 && s[i] == ' ') { 7 i--; 8 } 9 if (i < 0) { 10 break; 11 } 12 13 string word; 14 while (i >= 0 && s[i] != ' ') { 15 word += s[i]; 16 i--; 17 } 18 reverse(word.begin(), word.end()); 19 if (!result.empty()) { 20 result += ' '; 21 } 22 result += word; 23 } 24 s = result; 25 } 26 };
细节处理。
186 Reverse Words in a String II
1 class Solution { 2 public: 3 void reverseWords(string& s) { 4 reverse(s, 0, s.length); 5 for (int i=0, j=0; j<=s.length; j++) { 6 if (j==s.length || s[j]==' ') { 7 reverse(s, i, j); 8 i = j + 1; 9 } 10 } 11 } 12 13 void reverse(string& s, int begin, int end) { 14 while (begin < end - 1) { 15 swap(s[begin], s[end - 1]); 16 begin++; end--; 17 } 18 } 19 };
是上一题的简化版。先翻转整个string,再逐个单词翻转。其中,专门用一个下标 i 来指示单词的起始位置。
233 number of digit 1s