1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public String removeDuplicates(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) { sb.deleteCharAt(sb.length() - 1); } else { sb.append(c); } }
return sb.toString(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public String removeDuplicates(String s) { char[] chars = new char[s.length()];
int i = 0, j = 0; while (j < s.length()) { chars[i] = s.charAt(j); if (i > 0 && chars[i] == chars[i - 1]) { i -= 2; } j++; i++; }
return new String(chars, 0, i); } }
|
References
1047. Remove All Adjacent Duplicates In String