Leetcode 1047. Remove all adjacent duplicates in a string

Leetcode 1047. Remove all adjacent duplicates in a string

topic

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

Example:

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

Ideas

  • The meaning of this question is-every time you select 2 repeated adjacent letters to delete, it does not mean that all repeated adjacent letters are deleted
  • Just give a chestnut to understand
"aaa"
错误的结果:""
正确的结果:"a"
  • After clarifying this, just repeat the operation

Code

class Solution {
public:
    string simplify(string str) {
        for (int i = 0;i < str.size();++i) {
            if (i + 1 < str.size() && str[i + 1] == str[i]) {
                str.erase(str.begin() + i, str.begin() + i + 2);
                --i;
            }
        }

        return str;
    }

    string removeDuplicates(string S) {
        while (S != simplify(S)) {
            S = simplify(S);
        }

        return S;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/112303409