1047. Remove All Adjacent Duplicates In String

在这里插入图片描述

做法比较有意思的一道题目。
方法一:栈

class Solution {
public:
    string removeDuplicates(string S) {
        stack<char> sc;
        for (char c : S) {
            if (!sc.empty() && sc.top() == c) 
                sc.pop();
            else
                sc.push(c);
        }
        stringstream ss;
        while (!sc.empty()) {
            ss << sc.top();
            sc.pop();
        }
        string retStr = ss.str();
        reverse(retStr.begin(), retStr.end());
        return retStr;
    }
};

当然,也可以用string本身来当栈,意思一样

class Solution {
public:
    string removeDuplicates(string S) {
        string retStr = "";
        for (char c : S) {
            if (!retStr.empty() && retStr.back() == c)
                retStr.pop_back();
            else
                retStr.push_back(c);
        }
        return retStr;
    }
};

方法二:双指针

class Solution {
public:
    string removeDuplicates(string S) {
        int i = 0;
        for (int j = 0; j < S.size(); ++j) {
            S[i++] = S[j];
            if (i > 1 && S[i-1] == S[i-2])
                i -= 2;
        }
        return S.substr(0, i);
    }
};

i指向的是下一个赋值的位置,j指向的是迭代的位置。每次i监测到连续两个一样,那么就回退两个。

posted @ 2019-10-04 22:14  于老师的父亲王老爷子  阅读(16)  评论(0)    收藏  举报