1 class Solution {
 2 public:
 3     string reverseWords(string s) {
 4         s.insert(0," ");
 5         string res="";
 6         int len = s.length();
 7         int left=len-1,right=len-1;
 8         while(right>=0){
 9             
10             while(right>=0&&s[right]==' ')
11                 right--;
12             
13             if(right<0)
14                 break;
15             left=right;
16             
17             while(s[left]!=' ')
18                 left--;
19             
20             for(int i=left+1;i<=right;i++)
21                 res.push_back(s[i]);
22             
23             res.push_back(' ');
24             right=left;
25         }
26         if(res.length()!=0)
27             res.pop_back();
28         return res;
29     }
30 };

从后往前扫,给原字符串前面加一个空格,就可以统一处理了

posted on 2019-10-31 15:15  高数考了59  阅读(112)  评论(0)    收藏  举报