remove 3 duplicates
private static void remove(String s) { if (s == null || s.length() == 0) { return; } StringBuilder sb = new StringBuilder(); Stack<Character> st1 = new Stack<>(); Stack<Integer> st2 = new Stack<>(); for (char c : s.toCharArray()) { if (!st2.isEmpty() && c != st1.peek() && st2.peek() >= 3) { st1.pop(); st2.pop(); } if (st2.isEmpty()) { st1.push(c); st2.push(1); } else if (c == st1.peek()) { int cnt = st2.pop(); cnt++; st2.push(cnt); } else { st1.push(c); st2.push(1); } } if (!st2.isEmpty() && st2.peek() >= 3) { st1.pop(); st2.pop(); } while (!st2.isEmpty()) { int cnt = st2.pop(); char c = st1.pop(); for (int i = 0; i < cnt; i++) { sb.append(c); } } System.out.println(sb.reverse().toString()); }