DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

Remove All Adjacent Duplicates in String II | LeetCode | Java

Intuition: It uses a stack of custom objects Node to keep track of characters and their counts.

Algorithm:

  1. It iterates through the characters of the input string s and checks if the current character matches the top character on the stack.
  2. If it does, and the count of consecutive occurrences reaches k, the characters are removed from the stack. If not, a new Node is pushed onto the stack with count 1.
  3. After processing the entire input string, the method constructs the resulting string by popping characters and counts from the stack and appending the characters the required number of times to a StringBuilder.
  4. The final result is the reversed version of the StringBuilder, which is returned as the output.
class Solution {
    public String removeDuplicates(String s, int k) {

        Stack<Node> stack = new Stack<>();

        for(char c : s.toCharArray()){
            if(!stack.isEmpty() && stack.peek().ch==c){
                if(++stack.peek().count==k)
                    stack.pop();
            }
            else{
                stack.push(new Node(c, 1));
            }
        }


        StringBuilder sb = new StringBuilder();

        while(!stack.isEmpty()){
            Node curr = stack.pop();
            char ch = curr.ch;
            int n = curr.count;

            for(int i=1; i<=n; i++)
                sb.append(ch);
        }


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

class Node{
    char ch;
    int count;
    Node(char ch, int count){
        this.ch = ch;
        this.count = count;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)