String Compression

题目
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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容