解答
package leetcode.editor.cn;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String compressString(String S) {
if (S == null || S.isEmpty() || S.length() == 1) {
return S;
}
char[] sca = S.toCharArray();
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1, length = sca.length; i < length; ++i) {
if (sca[i] == sca[i - 1]) {
++count;
} else {
sb.append(sca[i - 1]).append(count);
count = 1;
}
}
sb.append(sca[S.length() - 1]).append(count);
String cValue = sb.toString();
if (cValue.length() >= S.length()) {
return S;
}
return cValue;
}
}
//leetcode submit region end(Prohibit modification and deletion)
测试用例
package leetcode.editor.cn;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SolutionTest {
private Solution s = null;
@Before
public void setUp() throws Exception {
s = new Solution();
}
@Test
public void test1() {
String value = s.compressString("aabcccccaaa");
Assert.assertEquals("a2b1c5a3", value);
}
@Test
public void test2() {
String value = s.compressString("abbccd");
Assert.assertEquals("abbccd", value);
}
@Test
public void test3() {
String value = s.compressString("a");
Assert.assertEquals("a", value);
}
@Test
public void test4() {
String value = s.compressString("aa");
Assert.assertEquals("aa", value);
}
@Test
public void test5() {
String value = s.compressString("ab");
Assert.assertEquals("ab", value);
}
@Test
public void test6() {
String value = s.compressString("aaab");
Assert.assertEquals("aaab", value);
}
@Test
public void test7() {
String value = s.compressString("aaa");
Assert.assertEquals("a3", value);
}
@Test
public void test8() {
String value = s.compressString("bb");
Assert.assertEquals("bb", value);
}
}