LeetCode:38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"
/*题意:数前面一个数字有多少个重复的数字,计数到下一行。比如4的时候,计算 21, 有1个2,一个1,写下来就是 1211. 一次类推*/
class Solution {
public:
    string countAndSay(int n) {
                //1.从前到后计数,2.数字转string
        string tmpstr="1";
        string hstr;
        string::iterator itBeg;
        for (int hn=1; hn<n; ++hn)
        {
            hstr = tmpstr;
            tmpstr.clear();
            //遍历hstr, 计数,写到tmpstr
            itBeg = hstr.begin();
            char beforeCh = *itBeg;
            ++itBeg;
            int cnt=1;
            while(itBeg!=hstr.end()){
                if (beforeCh==*itBeg){
                    ++cnt;
                    ++itBeg;
                }
                else{
                    //将cnt 和 beforeCh 写入tmpstr
                    string tmpcntstr;
                    while (cnt)
                    {
                        int tn = cnt%10;
                        tmpcntstr.push_back(tn+'0');
                        cnt /= 10;
                    }
                    for(int i=tmpcntstr.length()-1; i>=0; --i)
                        tmpstr.push_back(tmpcntstr[i]);
                    tmpstr.push_back(beforeCh);
                    
                    beforeCh = *itBeg;
                    cnt = 1;
                    ++itBeg;
                }
                
            }//end while
            string tmpcntstr;
            while (cnt)
            {
                int tn = cnt%10;
                tmpcntstr.push_back(tn+'0');
                cnt /= 10;
            }
            for(int i=tmpcntstr.length()-1; i>=0; --i)
                tmpstr.push_back(tmpcntstr[i]);
            tmpstr.push_back(beforeCh);

        }//end for
        return tmpstr;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容