Skip to content

Instantly share code, notes, and snippets.

@leonw007
Created April 5, 2015 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonw007/ef69b87b8ec03c1a7d08 to your computer and use it in GitHub Desktop.
Save leonw007/ef69b87b8ec03c1a7d08 to your computer and use it in GitHub Desktop.
cc150-1.5
package ch1;
/*
1.5 Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become
a2blc5a3. If the "compressed" string would not become smaller than the original
string, your method should return the original string.
* When we want to add something to a string constantly and without knowing the total length,
* StringBuilder is a good choice.
* We check whether the adjacent elements are same. if so, we increase count number; if not, we output the count number,
* new character and reset the count number to 1.
* Please be aware that at the end, we cannot detect the different adjacent elements, but we still need to add the count number.
Time Complexity O(n) Space O(n)
*/
public class CompressString {
public static String compress(String arg) {
StringBuilder newString= new StringBuilder();
//i is pointer for given string
int count=1;
newString.append(arg.charAt(0));
for(int i=1; i<arg.length(); i++) {
if(arg.charAt(i) == arg.charAt(i-1)) {
count++;
}else {
newString.append(count);
newString.append(arg.charAt(i));
count=1;
}
if(i==arg.length()-1) {
newString.append(count);
}
}
if(newString.length()>=arg.length()){
return arg;
}else {
return newString.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "aabcccccaaa";
System.out.println(compress(test));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment