压缩字符串

59 阅读1分钟

给你一个字符数组 chars ,请使用下述算法压缩:

从一个空字符串 s 开始。对于 chars 中的每组 连续重复字符 :

如果这一组长度为 1 ,则将字符追加到 s 中。 否则,需要向 s 追加字符,后跟这一组的长度。 压缩后得到的字符串 s 不应该直接返回 ,需要转储到字符数组 chars 中。需要注意的是,如果组长度为 10 或 10 以上,则在 chars 数组中会被拆分为多个字符。

请在 修改完输入数组后 ,返回该数组的新长度。

你必须设计并实现一个只使用常量额外空间的算法来解决此问题。

来源:力扣(LeetCode) 链接:leetcode.cn/problems/st…

public class Compress {

    /**
     * 题解:
     *    本题目只能使用常量额外空间;所以在记录的时候,需要将所有的数据记录在chars上.
     *    write: 记录在chars上修改到的位置;
     * @param chars
     * @return
     */
    public int compress(char[] chars) {
        int n = chars.length;

        int write = 0;
        int left = 0;
        for(int read = 0; read < n; read++) {
           if (read == n - 1 || chars[read] != chars[read + 1]) {
               chars[write++] = chars[read];
               int nums = read - left + 1;
               if (nums > 1) {
                   int anchor = write;
                   while (nums > 0) {
                       chars[write++] = (char) (nums % 10 + '0');
                       nums = nums / 10;
                   }
                   reverse(chars, anchor, write - 1);
               }
               left = read + 1;
           }
        }

        return write;
    }

    public void reverse(char[] chars, int start, int end) {
        int i = start;
        int j = end;
        while (i < j) {
            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i++;
            j--;
        }
    }
}