LeetCode -- 722. 删除注释

发布时间 2023-08-05 18:20:33作者: 深渊之巅

 利用双指针来进行删除操作

 

class Solution {
public:
    vector<string> removeComments(vector<string>& source) {
        string str;
        for(auto it : source) str += it + "'";

        int n = str.size();
        vector<string> res;
        int i = 0, j = 0;

        while(i < n) {
            if(i + 1 < n && str[i] == '/' && str[i + 1] == '/') {
                while(str[i] != '\'') i ++ ;
            } else if (i + 1 < n && str[i] == '/' && str[i + 1] == '*') {
                i += 2;
                while(!(str[i] == '*' && str[i + 1] == '/')) i ++ ;
                i += 2;
            } else {
                str[j ++ ] = str[i ++ ];
            }
        }

        str = str.substr(0, j);
        int pre = 0, pos = str.find("'");
        while(pos != -1) {
            string ss = str.substr(pre, pos - pre);
            if(ss.size()) res.push_back(ss);
            pre = pos + 1;
            pos = str.find("'", pre);
        }

        return res;

    }
};