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

leetcode 443. String Compression

程序员文章站 2024-03-13 22:17:28
...
#include<stack>
class Solution {
public:
    int compress(vector<char>& chars) {
        char tmp=chars[0];
        int count =1;
        int sum = 0;
        int j=0;
        for(int i =1;i<=chars.size();i++)
        {
            if(i==chars.size()||tmp!=chars[i])
            {
                sum ++;
                chars[j]=tmp;
                j++;
                if(count!=1)
                {
                    stack<int> l;
                    while(count)
                    {   
                      int r = count%10;
                      l.push(r);
                      count = count/10;
                      sum++;
                    }
                    while(!l.empty())
                    {
                        chars[j] = l.top()+'0';
                        j++;
                        l.pop();
                    }

                 }
                 if(i!=chars.size())tmp = chars[i];
                count = 1;
            }                
            else if(tmp==chars[i])count ++;
           
        }
        return sum;
    }
};

 

 

#include<stack>
class Solution {
public:
    int compress(vector<char>& chars) {
        char tmp=chars[0];
        int count =1;
        int sum = 0;
        int j=0;
        for(int i =1;i<=chars.size();i++)
        {
            if(i==chars.size()||tmp!=chars[i])
            {
                sum ++;
                chars[j]=tmp;
                j++;
                if(count!=1)
                {
                     string s = to_string(count);
                     for(int k=0;k<s.size();k++) {chars[j]=s[k];j++;sum++;}
                 }
                 if(i!=chars.size())tmp = chars[i];
                count = 1;
            }                
            else if(tmp==chars[i])count ++;
           
        }
        return sum;
    }
};