压缩字符串

2020-04-06  本文已影响0人  MrHitchcock

  1. 使用读写双指针 read & write
  2. 添加 anchor 指针 代表连续字符串的起始位置
  3. 当read指针 + 1 等于字符串长度 或 read指针 + 1不指向同一字符时,开始write
    4.write指针写入内容包括当前anchor指针指向的字符,以及(read - anchor + 1)的字符长度
class Solution(object):
    def compress(self, chars):
        anchor = write = 0
        for read, c in enumerate(chars):
            if read + 1 == len(chars) or chars[read + 1] != c:
                chars[write] = chars[anchor]
                write += 1
                if read > anchor:
                    for digit in str(read - anchor + 1):
                        chars[write] = digit
                        write += 1
                anchor = read + 1
        return write

class Solution {
    public int compress(char[] chars) {
        int anchor = 0, write = 0;
        for (int read = 0; read < chars.length; read++) {
            if (read + 1 == chars.length || chars[read + 1] != chars[read]) {
                chars[write++] = chars[anchor];
                if (read > anchor) {
                    for (char c: ("" + (read - anchor + 1)).toCharArray()) {
                        chars[write++] = c;
                    }
                }
                anchor = read + 1;
            }
        }
        return write;
    }
}

上一篇下一篇

猜你喜欢

热点阅读