Skip to content

Instantly share code, notes, and snippets.

@kinshuk4
Last active November 8, 2023 19:18
Show Gist options
  • Save kinshuk4/1a4d64f884b5d51792a992977366e40c to your computer and use it in GitHub Desktop.
Save kinshuk4/1a4d64f884b5d51792a992977366e40c to your computer and use it in GitHub Desktop.
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. The method signature is: “public static String compress(String inpu…
/*
* Implement a method to perform basic string compression using
* the counts of repeated characters. For example, the string aabcccccaaa
* would become a2b1c5a3. If the "compressed" string would not become
* smaller than the original string, your method should return the original string.
*/
public static String compresString(String text) {
int length = text.length();
/*
* Compression makes sense at length of larger than or equal to 3.
* For instance: "aaa" -> "a3"
*/
if(length > 2) {
String compressedText = "";
char lastChar = text.charAt(0);
int charCount = 1;
for(int i = 1; i < length; i++) {
if(text.charAt(i) == lastChar) charCount++;
else {
compressedText += Character.toString(lastChar) + Integer.toString(charCount);
lastChar = text.charAt(i);
charCount = 1;
}
}
compressedText += Character.toString(lastChar) + Integer.toString(charCount);
if(compressedText.length() < length)
return compressedText;
} return text;
}
@kinshuk4
Copy link
Author

kinshuk4 commented Nov 8, 2023

Thanks @edihasaj and @vinaygupta2255 - Yes, using StringBuilder makes sense!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment