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)StringBuilder.deleteCharAt(i)
is O(N), performance is : O(N) + O(N) = O(N).
Please criticcritique 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: ay
Input: caaabbbaacdddd Output: Empty String
Input: acaaabbbacdddd Output: acac
Input: azxxzy
Output: ayInput: caaabbbaacdddd
Output: Empty StringInput: acaaabbbacdddd
Output: acac