How to remove a pair of same adjacent characters from string in Java

1 Answer

0 votes
public class MyClass {
    public static String removeAdjacentPair(String s) {
        StringBuilder sb = new StringBuilder(s);
        int i = 0;
        while (i < sb.length() - 1) {
            if (sb.charAt(i) == sb.charAt(i + 1)) {
                sb.delete(i, i + 2);
                if (i != 0)
                    i--;
            } else
                i++;
        }
        return sb.toString();
    }
    public static void main(String args[]) {
        String s = "aabcccdeeffffgac"; 

        s = removeAdjacentPair(s);
        
        System.out.println(s);
    }
}



/*
run:

bcdgac

*/

 



answered Jun 20, 2020 by avibootz
...