Skip to content

Instantly share code, notes, and snippets.

@gokhanaliccii
Created October 23, 2014 09:31
Show Gist options
  • Save gokhanaliccii/e073b7ae235f5eea8a65 to your computer and use it in GitHub Desktop.
Save gokhanaliccii/e073b7ae235f5eea8a65 to your computer and use it in GitHub Desktop.
public class LimitedConsecutiveCharacter {
// http://java.dzone.com/articles/my-favorite-coding-interview
public static void main(String[] args) {
System.out.println(removeExtraCharacters("aaab", 2));
System.out.println(removeExtraCharacters("aabb", 1));
System.out.println(removeExtraCharacters("aabbaa", 1));
}
public static String removeExtraCharacters(String input, int maxConsequtiveChars) {
if (input == null || input.length() <= 1)
return input;
StringBuilder sb = new StringBuilder();
char buffer[] = input.toCharArray();
char previousChar = buffer[0];
int seen = 0;
for (int i = 1; i < buffer.length; i++) {
if (buffer[i] == previousChar && (++seen > maxConsequtiveChars)) {
continue;
}
previousChar = buffer[i];
sb.append(buffer[i]);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment