443. 压缩字符串

111 阅读1分钟

题目

image.png

image.png

image.png

思路

  • 三指针,i,j用来读,write用来写

7D3CC845ECB5A5EFAC2035CE1AD60CCF.png

代码

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;
    }
}