213 · String Compression - LintCode
# Description
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa
would become a2b1c5a3
.
If the "compressed" string would not become smaller than the original string, your method should return the original string.
You can assume the string has only upper and lower case letters (a-z).
# Example
Example 1:
Input: str = "aabcccccaaa"
Output: "a2b1c5a3"
Example 2:
Input: str = "aabbcc"
Output: "aabbcc"
# Solution
public class Solution { | |
/** | |
* @param originalString: a string | |
* @return: a compressed string | |
*/ | |
public String compress(String originalString) { | |
String s = originalString; | |
if (s == null || s.length() == 0) return s; | |
int count = 1; | |
char cur = s.charAt(0); | |
String res = ""; | |
for (int i = 1; i < s.length(); i++) { | |
if (cur == s.charAt(i)) { | |
count++; | |
} else { | |
res = res + cur + count; | |
count = 1; | |
cur = s.charAt(i); | |
} | |
} | |
//last one | |
res = res + cur + count; | |
if (res.length() >= s.length()) return s; | |
return res; | |
} | |
} |