public static String getShortString(String str) {
String shortString=null;
for(int i=0;i<str.length();i++) {
if(i==0) {
shortString=str.charAt(0)+"";
}else {
char last=shortString.charAt(shortString.length()-1);
char present=str.charAt(i);
if(last!=present) {
shortString+=present;
}
}
}
if(shortString.length()<=3) {
return shortString;
}
for(int i=0;i<shortString.length();i++) {
for(int j=2;j<shortString.length()-i;j++) {
if(i+j*2>shortString.length()) {
break;
}
String oneIndex=shortString.substring(i,i+j);
String twoIndex=shortString.substring(i+j,i+j*2);
if(oneIndex.equals(twoIndex)) {
shortString=shortString.substring(0,i)+oneIndex+shortString.substring(i+j*2,shortString.length());
//为了避免前面后面的凑到一起还是能压缩的情况
i=0;
break;
}
}
}
return shortString;
}
压缩字符串
最新推荐文章于 2024-06-02 13:11:39 发布