题目描述:用Java实现一个字符串压缩算法
Input : "aaabbacc"
Output:"3a2b1a2c"
/**
* Created by Eakon on 2017/6/16.
*
* 字符串压缩
*
* Input:
* aaabbacc
*
* Output:
* 3a2b1a2c
*/
public class StringCompression {
public static String stringCompression(String str){
StringBuilder sb = new StringBuilder("");
if(str!=null&&str.length()!=0){
for(int i=0; i<str.length(); i++){
char ch=str.charAt(i);
int count=1;
while(i+1<str.length()){
if((i+1)<str.length()&&(ch==str.charAt(i+1))){
i++;
count++;
}
else break;
}
sb.append(count).append(ch);
}
}
return sb.toString();
}
public static void main(String[] args) {
String str="aaabbacc";
String result=stringCompression(str);
System.out.println("压缩前:"+str);
System.out.println("压缩后:"+result);
}
}