利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”会变为"a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
package test;
public class Compress {
public static String compress(String str){
if(str==null || str.length()==0)
return str;
char curr = str.charAt(0);
int count = 1;
StringBuffer sb = new StringBuffer();
for(int i=1; i<str.length(); i++){
if(str.charAt(i)==curr)
count++;
else{
sb.append(curr);
sb.append(count);
curr=str.charAt(i);
count = 1;
}
}
sb.append(curr);
sb.append(count);
if(sb.length()>=str.length())
return str;
else
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String case1 = null;
String case2 = "";
String case3 = "abcde";
String case4 = "aabbcc";
String case5 = "aaabbcc";
String result = compress(case1);
System.out.println(result);
}
}