题目
思路
- 三指针,i,j用来读,write用来写
代码
class Solution {
public int compress(char[] chars) {
int length = chars.length;
int i = 0, j = 0, write = 0;//i,j用来读,write用来写
while (j < length) {
//找连续重复段的结尾
while (j < length && chars[j] == chars[i]) {
j++;
}
int times = j - i; //重复了多少个
chars[write] = chars[i];//先写重复的是啥字符
write++;
//如果重复次数大于1,记录重复次数,要逐位拆分
if (times > 1) {
String str = String.valueOf(times);
for (int k = 0; k < str.length(); k++) {
chars[write] = str.charAt(k);
write++;
}
}
i = j;//到下一个字符
}
return write;
}
}