Last active
August 29, 2015 14:02
-
-
Save UncleGarden/6ea4bdb039d7f0b1fd0a to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* 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
commented
Jun 22, 2014
- target.isEmpty() is not necessary since you have checked target.length() <= 2. (Line 13)
- 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