Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Last active August 29, 2015 14:02
Show Gist options
  • Save UncleGarden/6ea4bdb039d7f0b1fd0a to your computer and use it in GitHub Desktop.
Save UncleGarden/6ea4bdb039d7f0b1fd0a to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 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.
*
* @author Jiateng
*/
public class CC1_5 {
public static String compression(String target) {
if (target == null || target.isEmpty() || target.length() <= 2) {
return target;
}
char[] array = target.toCharArray();
StringBuilder result = new StringBuilder();
int count = 1;
char prev = target.charAt(0);
char cur;
for (int i = 1; i < array.length; i++) {
cur = target.charAt(i);
if (cur == prev) {
count++;
} else {
result.append(prev);
result.append(count);
prev = cur;
count = 1;
}
}
//add the last character and count
result.append(prev);
result.append(count);
//compare the length
return result.length() < array.length ? result.toString() : new String(array);
}
public static void main(String[] args) {
System.out.println(compression("abcdefg"));
System.out.println(compression("aaabbbbddddiiiifffegnnnnn"));
}
}
@jason51122
Copy link

  1. target.isEmpty() is not necessary since you have checked target.length() <= 2. (Line 13)
  2. You can reach your goal without using StringBuilder. Have a try.

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