LeetCode_Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, ...



1 is read off as "one 1" or 11.

11 is read off as "two 1s" or 21.

21 is read off as "one 2, then one 1" or 1211.



Given an integer n, generate the nth sequence.



Note: The sequence of integers will be represented as a string.

弄清楚序列产生的规律,剩下的就是string的处理,比较简单

class Solution {

public:

    string countAndSay(int n) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        string A = "1", B="";

        int count ;

        for(int i = 1;i < n; i++)

        {

             int m = A.length();

             count = 1;

             for(int j = 0; j< m-1 ;j++)

             {

                if(A[j] == A[j+1])

                  count++;

                  else

                     {

                        B+=char('0'+count);

                        B+=A[j];

                        count=1;

                     }

             }

            

            B+=char('0'+count);

            B+=A[m-1];

            A = B;

            B = "";

        }

        

        return A ;

    }

};

 

你可能感兴趣的:(LeetCode)