Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 1209. Remove All Adjacent Duplicates in String II #109

Open
Woodyiiiiiii opened this issue May 6, 2022 · 0 comments
Open

LeetCode 1209. Remove All Adjacent Duplicates in String II #109

Woodyiiiiiii opened this issue May 6, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题关键是遍历到每个字符,要跟前面的字符匹配并计数,还涉及到消除。所以关键是要想到用,用栈保存字符和它出现次数。

class Solution {
    public String removeDuplicates(String s, int k) {
        
        Stack<Pair> stack = new Stack<>();
        int n = s.length();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (stack.isEmpty() || stack.peek().c != c) {
                stack.push(new Pair(c, 1));
                sb.append(c);
            } else {
                Pair pair = stack.peek();
                pair.count++;
                sb.append(c);
                if (pair.count == k) {
                    stack.pop();
                    sb.delete(sb.length() - k, sb.length());
                }
            }
        }

        return sb.toString();
        
    }
}

class Pair {

    public char c;

    public int count;

    public Pair(char c, int count) {
        this.c = c;
        this.count = count;
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant