My 3ms C++ code


  • 0
    Z
    class Solution {
    public:
        string countAndSay(int n) {
            vector<string> sequence(n);
            sequence[0]="1";
            for(int i=1;i<n;i++){
                sequence[i]=count_and_say(sequence[i-1]);
            }
            return sequence[n-1];
        }
        
        string count_and_say(string n){
            int len=n.size();
            int count=0;
            string res;
            char obj=n.at(0);
            for(int i=0;i<len;i++){
                if(n.at(i)==obj)
                count++;
                else{
                    res+=count+'0';//may be wrong when count>9
                    res+=obj;
                    obj=n.at(i);
                    count=1;
                }
            }
            if(count>1){
                res+=count+'0';
                res+=obj;
            }
            else{
                res+=1+'0';
                res+=n.at(len-1);
            }
            return res;
        }
    };
    

    The solution should be wrong when count>9. But there is just 18 test cases for this problem.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.