I need to write a function that receives a String and removes adjacent duplicates.
Example:
Input -> "aabbaabbcccaaa"
Output -> "ababca"
I tried to solve it as follows:
public String remdups(String input) {
String response = "";
char temp;
int i, length = input.length();
for(i = 0; i < length; i++) {
temp = input.charAt(i);
response += temp;
while(i < length && input.charAt(i) == temp) i++;
}
return response;
}
But it seems that time complexity is not as expected, how could I improve perfomance or what would be a better approach? I know it's a really simple problem, but I can't find a way to improve or another way to do it.
To me your code looks already good from a complexity point of view. It is only going through the String once. The optimisations you could do are on the response String
by using a StringBuilder
, and maybe simplifying the loop a bit just for readability (no need for 2 nested loops, and incrementing the i
counter from 2 places could introduce mistakes).
public String remdups(String input) {
StringBuilder response = new StringBuilder(input.length());
char temp;
for (int i = 0; i < input.length(); i++) {
char next = input.charAt(i);
if (temp != next) {
temp = next;
response.append(temp);
}
}
return response.toString();
}