1209. 删除字符串中的所有相邻重复项 II

给你一个字符串 s,「k 倍重复项删除操作」将会从 s 中选择 k 个相邻且相等的字母,并删除它们,使被删去的字符串的左侧和右侧连在一起。

你需要对 s 重复进行无限次这样的删除操作,直到无法继续为止。

在执行完所有删除操作后,返回最终得到的字符串。

本题答案保证唯一。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Scanner;
import java.util.Stack;

class Solution {
    public String removeDuplicates(String s, int k) {
        if (s == null || s.length() == 0) {
            return "";
        }
        Stack<Info> stack = new Stack<>();
        int num = 1;
        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) == s.charAt(i - 1)) {
                num++;
            } else {
                num %= k;
                if (num != 0) {
                    if (!stack.isEmpty() && stack.peek().value == s.charAt(i - 1)) {
                        Info pop = stack.pop();
                        pop.num += num;
                        pop.num %= k;
                        if (pop.num != 0) {
                            stack.push(pop);
                        }
                    } else {
                        stack.push(new Info(s.charAt(i - 1), num));
                    }
                }
                num = 1;
            }
        }

        num %= k;
        if (num != 0) {
            if (!stack.isEmpty() && stack.peek().value == s.charAt(s.length() - 1)) {
                Info pop = stack.pop();
                pop.num += num;
                pop.num %= k;
                if (pop.num != 0) {
                    stack.push(pop);
                }
            } else {
                stack.push(new Info(s.charAt(s.length() - 1), num));
            }
        }

        StringBuilder ans = new StringBuilder();
        while (!stack.isEmpty()) {
            Info info = stack.pop();
            for (int i = 1; i <= info.num; ++i) {
                ans.append(info.value);
            }
        }

        return ans.reverse().toString();
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().removeDuplicates(in.next(), in.nextInt()));
        }
    }
}

class Info {
    char value;
    int num;

    public Info(char value, int num) {
        this.value = value;
        this.num = num;
    }
}
posted @ 2022-01-21 12:29  Tianyiya  阅读(47)  评论(0)    收藏  举报