题目
利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。如字符串aabcccccaaa会变成a2bc5a3。
代码:
public class CompressSeqSame {
public static void main(String[] args) {
System.out.println(compress(""));
System.out.println(compress(null));
System.out.println(compress("abbbccde"));
System.out.println(compress("aaabbbccdezzzz"));
System.out.println(compress("abbbccdefzzzffe"));
System.out.println(compress("abbbccdezzdd"));
System.out.println(compress("abbbccdeddz"));
System.out.println(compress("abcdefg"));
}
private static String compress(String orign){
if(null == orign || orign.length()==0){
return orign;
}
String des = "";
char last = orign.charAt(0);
int count = 1;
for(int i=1;i<orign.length();i++){
if(last==orign.charAt(i)){
++count;
}else{
des+=last+""+(count==1?"":count);
last = orign.charAt(i);
count = 1;
}
}
return des+last+(count==1?"":count);
}
}
输出结果:
null
ab3c2de
a3b3c2dez4
ab3c2defz3f2e
ab3c2dez2d2
ab3c2ded2z
abcdefg