LeetCode38 报数

/*

C++ string内部似乎还是char数组?末尾是'',str[length()]不会抛异常。

*/

我的代码:

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        string tem="";
        int cont=0;
        
        for(int i=1;i<n;i++){
            for(int j=0;j<res.size();j++){
                cont++;
                if((j+1)==res.length()||res[j+1]!=res[j]){
                    //char
                    tem+=cont+'0';
                    tem+=res[j];
                    cont=0;
                    
                }
                
            }
            res=tem;
            tem="";
        }
        return res;
    }
};

最快代码:

class Solution {
public:
    string countAndSay(int n) {
       if(n==0) return "";
    
    string str="1" ;//开始报数为1 
    
    for(int i=1;i<n;i++)
    {
        string temp;//用于表征几个重复的数字个数 
        int count=1; //用于计算有几个重复的
        for(int j=0;j<str.length();j++)
        {
            if(str[j]==str[j+1])
               count++;
            else
            {
                temp+=('0'+count);
                temp+=str[j];//表示出几个几 
                count=1;                
            } 
        }
        str=temp;        
    }  
    return str;   
    }
};

原文地址:https://www.cnblogs.com/azureice/p/leetcode38.html