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

[leetcode]443. String Compression

程序员文章站 2024-03-13 22:17: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.

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

分析:

原地压缩字符串,要求为每个字符只保留一个,后面为该字符原来出现的次数,最终返回新数组的长度。用变量cur来定位新数组中元素的位置,i来定位原数组中每个字符第一次出现的位置,j来记录每个字符出现的个数,转化为字符加入数组cur的后一位。

class Solution {
public:
    int compress(vector<char>& chars) {        
        int len = chars.size();
        int cur = 0;
        for(int i = 0 , j = 0; i < len; i = j)
        {
            while(j < len && chars[i] == chars[j])
                j++;
            chars[cur++] = chars[i];
            if(j - i == 1)
                continue;
            for(char c : to_string(j - i))
                chars[cur++] = c;               
        }
        return cur;               
    }
};