美文网首页Leetcode
Leetcode 443. String Compression

Leetcode 443. String Compression

作者: SnailTyan | 来源:发表于2018-10-09 17:56 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    String Compression

    2. Solution

    class Solution {
    public:
        int compress(vector<char>& chars) {
            if(chars.size() == 0 || chars.size() == 1) {
                return chars.size();
            }
            int count = 1;
            int index = 0;
            char current = chars[0];
            for(int i = 1; i < chars.size(); i++) {
                if(chars[i] != current) {
                    chars[index] = current;
                    index++;
                    if(count > 1) {
                        string temp = to_string(count);
                        for(char ch : temp) {
                            chars[index] = ch;
                            index++;
                        }
                    }
                    count = 1;
                    current = chars[i];
                }
                else {
                    count++;
                }
            }
            chars[index] = current;
            index++;
            if(count > 1) {
                for(char ch : to_string(count)) {
                    chars[index] = ch;
                    index++;
                }
            }
            return index;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/string-compression/description/

    相关文章

      网友评论

        本文标题:Leetcode 443. String Compression

        本文链接:https://www.haomeiwen.com/subject/dkdyaftx.html