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 };
View Code

相关文章:

  • 2021-06-17
  • 2021-07-28
  • 2022-02-24
  • 2021-08-28
  • 2021-11-08
  • 2021-07-25
  • 2022-12-23
猜你喜欢
  • 2021-06-05
  • 2022-01-29
  • 2021-08-08
  • 2022-02-07
  • 2021-11-12
  • 2022-01-24
相关资源
相似解决方案