leetcode新题,好久没更新了的感觉

 

class Solution {
public:
    void reverseWords(string &s) {
        vector<string> res;
        int i = 0;
        int len = s.size();
        //trim
        while(s[i] == ' ' && i < len) i++;
        while(s[len-1] == ' ' && i < len) len--;
        
        while(i < len) {
            int start = i;
            if(s[start] != ' ') {
                while(i < len && s[i] != ' ')i++;
                res.push_back(s.substr(start , i - start));
            } else {
                while(i < len && s[i] == ' ') i++;
                res.push_back(" ");
            }
        }
        reverse(res.begin() , res.end());
        s = "";
        for(auto const &x : res)
            s += x;
    }
};

就是一个简单的parser,把每个token放到vector里面,然后从后到前处理下就ok。

记得前后有空格是不算的。。所以要处理掉

多个空格按一个空格算。

相关文章:

  • 2021-10-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-10-29
  • 2022-01-14
  • 2021-07-20
猜你喜欢
  • 2022-01-27
  • 2022-02-11
  • 2021-12-04
  • 2021-08-21
  • 2021-10-01
  • 2021-09-10
  • 2022-02-22
相关资源
相似解决方案