给你一个字符数组 chars ,请使用下述算法压缩:
从一个空字符串 s 开始。对于 chars 中的每组 连续重复字符 :
如果这一组长度为 1 ,则将字符追加到 s 中。
否则,需要向 s 追加字符,后跟这一组的长度。
压缩后得到的字符串 s 不应该直接返回 ,需要转储到字符数组 chars 中。需要注意的是,如果组长度为 10 或 10 以上,则在 chars 数组中会被拆分为多个字符。
请在 修改完输入数组后 ,返回该数组的新长度。
你必须设计并实现一个只使用常量额外空间的算法来解决此问题。
public class ts1 {
public static int compress(char[] chars) {
int cnt=0;
int sum=0;
for(int i=0;i<chars.length;i++){
for(int j=i+1;j<chars.length;j++){
if(chars[i]==chars[j] && chars[j]!='0'){
chars[j]='0';
cnt++;
if(cnt>10){
sum++;
cnt=0;
}
}else{
break;
}
if(cnt>0){
sum++;
cnt=0;
}
}
}
int c = 0;
for(int i=0;i<chars.length;i++){
if(chars[i]!='0'){
c++;
}
}
System.out.println("c "+c);
System.out.println("sum "+sum);
System.out.println("cnt "+cnt);
c = c+sum+cnt;
return c;
}
public static void main(String[] args) {
char[] af = {'a','a','b','b','c','c','d','d'};
int a = compress(af);
System.out.println(a);
}
}