Sunday, July 2, 2017

Remove all adjacent or consecutive duplicate characters

Remove all adjacent or consecutive duplicate characters


Input:  azxxzy
Output: ay
First "azxxzy" is reduced to "azzy". The string "azzy" contains duplicates, 
so it is further reduced to "ay".

Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to "gksforgg". The string "gksforgg" contains 
duplicates, so it is further reduced to "gksfor".

Input: caaabbbaacdddd
Output: Empty String

Input: acaaabbbacdddd
Output: acac

Iterate through the characters and keep track of duplicates with start and end index, once you get a non matching character then delete the start to end characters and step back one more step and start again.

private static String removeAllAdjacentDuplicates(String s) {
StringBuilder sb = new StringBuilder(s);
int startIndex = -1;
int endIndex = -1;
char previousChar = '\0';
for (int i = 0; i < sb.length(); i++) {
if (previousChar == sb.charAt(i))
endIndex = i;
else {
if (endIndex > startIndex) {
sb.delete(startIndex, endIndex + 1);
i = --startIndex;
i = i < 0 ? 0 : i;
endIndex = -1;
}
startIndex = i;
previousChar = sb.charAt(i);
}
}
if (endIndex > startIndex)
sb.delete(startIndex, endIndex + 1);

return sb.toString();
}

Note: Deleting is a costly operation for that all the elements will be left shifted with their position.

1 comment:

  1. We may modify the phrases of this Promotion or terminate this Promotion at any time. When you 1xbet korea successfully complete Verification, you'll receive another e mail with a "claim-link" relating to your $20 registration Bonus ("Claim Email"). You must click on on the claim-link in the Claim Email within 48 hours of receipt of the Claim Email ("Claim"), or your Bonus will be forfeited. Stay up-to-date with the latest promotion provides and information. It’s best for anybody who’s planning to put a lot of bets, and who doesn’t thoughts making quantity of|numerous|a variety of} consecutive deposits over the course of a week. This is a 280% up to as} $14,000 welcome bonus that covers your first 5 deposits.

    ReplyDelete