How to remove all adjacent duplicate characters from a string until no more can be removed in Java

1 Answer

0 votes
public class Main {

    public static String removeAdjacentDuplicates(String s) {
        StringBuilder stack = new StringBuilder();

        for (char ch : s.toCharArray()) {
            int n = stack.length();
            if (n > 0 && stack.charAt(n - 1) == ch) {
                stack.deleteCharAt(n - 1);   // pop
            } else {
                stack.append(ch);            // push
            }
        }

        return stack.toString();
    }

    public static void main(String[] args) {
        String s = "abbacccada";

        System.out.println(removeAdjacentDuplicates(s));   
    }
}


/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...