Created
June 21, 2014 00:22
-
-
Save nealhu/f633212a765f31388f5b to your computer and use it in GitHub Desktop.
CC_1_5
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
// Cracking the Coding Interview | |
// 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. | |
class StringCompress { | |
public static String compressString(String s) { | |
if (s == null) return null; | |
boolean needCompressing = false; | |
for(int i = 0; i < s.length(); i++) { | |
int dupNum = countDuplicateChar(s, i); | |
if (dupNum > 1) { | |
needCompressing = true; | |
break; | |
} | |
i += dupNum; | |
} | |
if (needCompressing) { | |
StringBuffer b = new StringBuffer(); | |
for(int i = 0; i < s.length(); i++) { | |
int dupNum = countDuplicateChar(s, i); | |
b.append(s.charAt(i)); | |
if (dupNum > 0) { | |
b.append(dupNum+1); | |
} | |
i += dupNum; | |
} | |
return b.toString(); | |
} else { | |
return s; | |
} | |
} | |
private static int countDuplicateChar(String s, int start) { | |
int count = 0; | |
for(int i = start+1; i < s.length(); i++) { | |
if (s.charAt(i) == s.charAt(start)) { | |
count++; | |
} else { | |
return count; | |
} | |
} | |
return count; | |
} | |
public static void main(String[] args) { | |
assert "".equals(compressString("")); | |
assert compressString(null) == null; | |
assert "a".equals(compressString("a")); | |
assert "ab".equals(compressString("ab")); | |
assert "abb".equals(compressString("abb")); | |
assert "aa".equals(compressString("aa")); | |
assert "ab3c2".equals(compressString("abbbcc")); | |
assert " 4".equals(compressString(" ")); | |
System.out.println("Test Passed"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment