欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

String Compression

程序员文章站 2022-03-12 17:10:40
...

题目
Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

Follow up:
Could you solve it using only O(1) extra space?

答案

class Solution {
    public int compress(char[] chars) {
        int insert = 0;
        for(int i = 0; i < chars.length; i++) {
            // For each char, look right until a different char is seen
            int r = i + 1;
            while(r < chars.length && chars[r] == chars[i]) {
                r++;
            }
            // place character
            chars[insert++] = chars[i];

            // place occurence
            int count = r - i;
            if(count > 1) {
                String num = Integer.toString(count);
                for(int j = 0; j < num.length(); j++) {
                    chars[insert++] = num.charAt(j);
                }
            }
            i = r - 1;
        }
        return insert;
    }
}