Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created June 17, 2014 12:42
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 chouclee/b57b6915366b87cdff44 to your computer and use it in GitHub Desktop.
Save chouclee/b57b6915366b87cdff44 to your computer and use it in GitHub Desktop.
[CC150][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.
public class compressStr {
public static String compress(String s) {
StringBuilder sb = new StringBuilder();
int idx = 0;
int l = s.length();
boolean first = true;
int count = 0;
while (idx < l) {
if (first) {
sb.append(s.charAt(idx++));
count = 1;
first = false;
if (idx == l)
sb.append('1');
}
else {
while (idx < l && s.charAt(idx) == s.charAt(idx - 1)) {
idx++;
count++;
}
sb.append(String.valueOf(count));
first = true;
}
}
String newStr = sb.toString();
return (newStr.length() < l) ? newStr : s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(compressStr.compress("aaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(compressStr.compress("aaaaabbbbb "));
System.out.println(compressStr.compress(""));
System.out.println(compressStr.compress("abc"));
System.out.println(compressStr.compress("aaaabbbbc"));
System.out.println(compressStr.compress("呵呵呵呵呵呵"));
System.out.println(compressStr.compress("呵呵"));
System.out.println(compressStr.compress("呵"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment