For this problem, I came up with this ugly solution of appending the characters to the output and in case there is adjacent duplicate deleting from the output. Considering StringBuilder.deleteCharAt(i)
is O(N), performance is O(N) + O(N) = O(N).
Please critique this, if this is a right way.
public static String removeDuplicate(String s) {
StringBuilder builder = new StringBuilder();
char lastchar = '\0';
for (int i = 0; i < s.length(); i++) {
String str = builder.toString();
if (!str.equals("")
&& (str.charAt(str.length() - 1) == s.charAt(i))) {
builder.deleteCharAt(str.length() - 1);
} else if (s.charAt(i) != lastchar)
builder.append(s.charAt(i));
lastchar = s.charAt(i);
}
return builder.toString();
}
Sample input outputs:
Input: azxxzy
Output: ayInput: caaabbbaacdddd
Output: Empty StringInput: acaaabbbacdddd
Output: acac
messy
it returnsmey
... I was expectingmesy
... which one is right? Why? \$\endgroup\$"messy"
→"mey"
. "Recursively remove" refers to the problem statement, not the implementation. \$\endgroup\$