输入"aabcccccaaa"
返回:“a2b1c5a3”
若压缩的字符串比原来短,返回压缩后的
否则,返回原来
import java.util.*;
public class kk {
public static void main(String[] args) {
String s = "aabcccccaaa";
compressString (s);
}
public static String compressString(String s) {
String[] s1 = s.split("");
StringBuffer sb = new StringBuffer();
sb.append(s1[0]);
int p=1;
for (int i =1;i<s1.length;i++) {
if(s1[i].equals(s1[i-1]))
{
p++;
}
else
{
//
sb.append(p);
sb.append(s1[i]);
p=1;
}
}
sb.append(p);
String re = sb.toString();
System.out.println(sb.toString());
if(re.length()< s.length())
{
return re;
}
return s;
}
}