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

面试题 01.06. 字符串压缩

程序员文章站 2024-03-04 09:54:47
...

面试题 01.06. 字符串压缩

class Solution {
public:
    string compressString(string S) {
        string s1="";
        int n=S.size();
        s1.insert(s1.begin(),S[0]);
        int a=1;
        for(int i=1;i<n;i++){
            if(S[i]==S[i-1]){
                a+=1;
            }
            else{
                // cout<<char(a)<<endl;
                if(a<=9)
                    s1.push_back(a+48);
                else {//当a>9例如a=100,转化为001分别取出每一位数并输入字符串
                    int temp=a;
                    int sum=0;
                    int j=0;
                    while(temp){
                        j+=1;
                        int num=temp%10;
                        
                        sum=num+10*sum;
                        temp=temp/10;
                    }
                    int t=sum;
                    int k=0;
                     while(t){k++;
                        int n=t%10;
                        s1.push_back(n+48);
                        t=t/10;
                    }
                    while(j!=k){
                        k++;
                        s1.push_back(48);
                    }
                    
                }
                s1.push_back(S[i]);
                a=1;
            }
            if(i==n-1){
                          int temp=a;
                    int sum=0;
                    int j=0;
                    while(temp){
                        j+=1;
                        int num=temp%10;
                        
                        sum=num+10*sum;
                        temp=temp/10;
                    }
                    int t=sum;
                    int k=0;
                     while(t){k++;
                        int n=t%10;
                        s1.push_back(n+48);
                        t=t/10;
                    }
                    while(j!=k){
                        k++;
                        s1.push_back(48);
                    }
            }
          
        }
        return s1.size()<n?s1:S;
    }
};
class Solution:
    def compressString(self, S: str) -> str:
        i=0
        res=''
        while i<len(S):
            j=i
            while j<len(S)and S[j]==S[i]:
                j+=1
            res+=S[i]+str(j-i)
            i=j;
        return res if len(res)<len(S) else S 
相关标签: leetcode