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;
}
@edihasaj
Copy link

It would be better to implement StringBuilder/StringBuffer for time/space complexity.

@vinaygupta2255
Copy link

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();
}

@vinaygupta2255
Copy link

vinaygupta2255 commented Oct 27, 2023

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();
}

@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