Last active
November 8, 2023 19:18
-
-
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…
This file contains 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
/* | |
* 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; | |
} |
public static String compress(String str) {
StringBuilder output = new StringBuilder();
for(int i = 0; i<str.length(); i++){
int val = 1;
while(i != str.length()-1 && str.charAt(i) == str.charAt(i+1)){
i++;
val++;
}
output.append(str.charAt(i));
String st = String.valueOf(val);
for(int k = 0;k<st.length();k++){
output.append(st.charAt(k));
}
}
return output.toString();
}
public static String compress1(String str) { // using MAP Solution MIMP
Map<Character, Integer> map = new LinkedHashMap<>();
for(int i = 0; i<str.length(); i++){
if(map.get(str.charAt(i)) != null) {
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}
else {
map.put(str.charAt(i), +1);
}
}
StringBuilder output = new StringBuilder();
for(Entry<Character, Integer> entry : map.entrySet()) {
output.append(entry.getKey());
output.append(entry.getValue());
}
return output.toString();
}
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
It would be better to implement StringBuilder/StringBuffer for time/space complexity.