难点主要是字符串中超过10次的元素
class Solution {
public int compress(char[] chars) {
int slow = 0, fast = 0;
while(fast < chars.length){
int count = 1;
while(fast + 1 < chars.length && chars[fast] == chars[fast + 1]){
++fast;
++count;
}
chars[slow++] = chars[fast++];
// 下面是本题难点
// 若count>10,需要从高到低,如12要拆分成'1''2'放到数组中,同时需要swap
// 若count<10,不用swap
if(count > 1){
int left = slow;
while(count > 0){
chars[slow++] = (char)(count % 10 + '0');
count /= 10;
}
int right = slow - 1;
while(left < right){
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
++left;--right;
}
}
}
return slow;
}
}