leetcode 1209. Remove All Adjacent Duplicates in String II(移掉相邻连接的重复字符 II)

You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

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

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

Example 1:

Input: s = “abcd”, k = 2
Output: “abcd”
Explanation: There’s nothing to delete.
Example 2:

Input: s = “deeedbbcccbdaa”, k = 3
Output: “aa”
Explanation:
First delete “eee” and “ccc”, get “ddbbbdaa”
Then delete “bbb”, get “dddaa”
Finally delete “ddd”, get “aa”

把所有相同的连续k个字符都去掉,去掉后剩下的拼在一起。
拼在一起后连续相同的k个继续去掉,直到没有相同的连续k个字符为止。

思路:
栈和计数。

用当前数组模拟栈,栈顶记为top。
top指向的字符记录它出现了多少次,
一旦满足出现了k次,把栈顶的k个元素都移出,top移到这k个元素之前。
否则压字符入栈。

最后输出栈中的字符。

    public String removeDuplicates(String s, int k) {
        int n = s.length();
        char[] str = s.toCharArray();
        int[] cnt = new int[n];
        int top = -1;
        
        for(int i = 0; i < n; i++) {
            if(top < 0) {
                top ++;
                str[top] = str[i];
                cnt[top] = 1;
            } else {
                if(str[top] == str[i] && cnt[top] + 1 == k) {
                    top -= k - 1;  //移到k个元素之前,top还没到k(cnt[top]+1),所以是k-1
                } else {
                    top ++; //即将压入栈的下一元素
                    cnt[top] = str[top - 1] == str[i] ? cnt[top - 1] + 1 : 1; //记入压入栈字符的计数
                    str[top] = str[i];  //新的字符压入栈
                }
            }
        }
        return new String(str, 0, top + 1);
    }

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值