Skip to content

Instantly share code, notes, and snippets.

@MelulekiDube
Created October 13, 2018 15:42
Show Gist options
  • Save MelulekiDube/9ccfb1e1e4273a7b44baa09284d5336b to your computer and use it in GitHub Desktop.
Save MelulekiDube/9ccfb1e1e4273a7b44baa09284d5336b to your computer and use it in GitHub Desktop.
public static String compressString(String originalString) {
if(originalString.length()<3) return originalString;
int freq = 1; //default value for the frequency is 1 to signal that we have seen atleast this character we tokinig abotu
StringBuilder compressedString = new StringBuilder();// we will build the answer here
int current_index = 1;
for (; current_index < originalString.length(); ++current_index) {
if (originalString.charAt(current_index - 1) == originalString.charAt(current_index)) {
++freq;
} else {//if they are not equal
compressedString.append(originalString.charAt(current_index - 1)).append(freq);
freq = 1;//to indicate we have seen the character at this index
}
}
compressedString.append(originalString.charAt(current_index-1)).append(freq);
return (compressedString.length() < originalString.length()) ? compressedString.toString() : originalString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment