My Iterative CPP Solution


  • 0
    C
    class Solution {
    public:
        int count_sequence(string::iterator &iter)
        {
            int cnt = 0;
            char ch = *iter;
            
            while(*iter && ch == *iter)
            {
                cnt++;
                iter++;
            }
            
            return cnt;
        }
        
        string countAndSay(int n) 
        {
            string s = "1";
            while(--n > 0)
            {
                string tmp;
                
                string::iterator iter = s.begin();
                while(*iter)
                {
                    int cnt = count_sequence(iter);
                    tmp.push_back(cnt + '0');
                    tmp.push_back( *(iter-1) );
                }
                
                s = tmp;
            }
            
            return s;
        }
    };

Log in to reply
 

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