Created
October 23, 2014 09:31
-
-
Save gokhanaliccii/e073b7ae235f5eea8a65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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