LeetCode(1047)删除字符串中所有相邻重复项

用子字符串是过不了的,超时,需要一个一个字符判断

class Solution {
public:
    string removeDuplicates(string s) {
        int n = s.size(),top = 0;
        if(n==1)return s;
        for(int i=0;i<n;i++){
            if(top==0||s[top-1]!=s[i]){
                s[top++] = s[i];
            }else{
                top--;
            }
        }
        s.resize(top);
        return s;
    }
};

 

posted @ 2022-06-07 09:20  智人心  阅读(26)  评论(0)    收藏  举报