1047. Remove All Adjacent Duplicates In String

Given a string S of lowercase letters, a  duplicate removal  consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.

Example 1:

Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

  1. 1 <= S.length <= 20000
  2. S consists only of English lowercase letters.

这道题给了一个字符串,让移除所有相邻的重复字符,注意之前不相邻的字符可以在其他字符移除后变的相邻,从而形成的新的相邻的重复字符,所以只是简单移除一次不能保证能得到最终的结果。这里需要借助栈的思路来做,可以用字符串来模拟栈的后入先出的特性。遍历每个字符,若 res 不空,且最后一个字符和当前字符相同,则移除掉 res 的最后一个字符,否则将当前字符加入 res 中,这样最后剩下的即为所求,参见代码如下:

解法一:

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

我们也可以使用双指针来做,两个指针i和j,其中i指向去除重复后的最后一个字符的位置,j为遍历字符串S的位置,首先将 S[j] 赋值给 S[i],然后看若i大于0,且 S[i-1] 和 S[i] 相等的,i自减2,这样就移除了重复,最后根据i的位置取出子串返回即可,参见代码如下:

解法二:

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

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1047

类似题目:

Remove All Adjacent Duplicates in String II

参考资料:

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/294893/JavaC%2B%2BPython-Two-Pointers-and-Stack-Solution

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/294964/JavaPython-3-three-easy-iterative-codes-w-brief-explanation-analysis-and-follow-up.

LeetCode All in One 题目讲解汇总(持续更新中…)


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,试运营期间前五十位可享受半价优惠~)

×

Help us with donation