My c++ code (2ms)


  • 0
    D
    // use two strings to generate the result string in a ping-pong way
    class Solution {
    public:
        string countAndSay(int n) {
            string s[2];
            int cur_s = 0, next_s=1;
            int count,  pos ,i ;
            char val;
            
            if(n<=0) return ""; // if invalid n, return null string
            else
            {
                s[next_s].push_back('1'); // start with "1"
                for(i=1; i<n; i++)
                {
                    cur_s = next_s; // switch cur and next string index, the result string from the previous iteration is the input of this iteration
                    next_s ^=0x1;
                    
                    count = 1;
    
                    for(pos=0; pos < s[cur_s].size()-1; pos++)
                    {
                        if(s[cur_s][pos+1] == s[cur_s][pos]) // always compare with the previous element 
                            {count++;}
                        else
                        {
                            s[next_s] += count + '0'; // save count
                            s[next_s] += s[cur_s][pos]; // save value
                            count = 1; 
                        }
                    }
                    s[next_s] += count + '0'; // save count
                    s[next_s] += s[cur_s][pos]; // save value
                
                    s[cur_s].clear(); // clear the current string for the next iteration
                }
                return s[next_s] ; 
            }// else
        }
    };

  • 0
    T

    What about count is greater than 10??


Log in to reply
 

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