[leetcode]38. Count and Say

来源:互联网 发布:淘宝网保安服装 编辑:程序博客网 时间:2024/06/01 10:23

题目链接:https://leetcode.com/problems/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.

class Solution {public:    string countAndSay(int n)    {        string currRes="";        if(n<=0)            return currRes;        string preRes="1";        if(n==1)            return preRes;        for(int i=1;i<n;i++)        {                    char tmp=preRes[0];            int times=1;            for(int j=1;j<preRes.size();j++)            {                if(preRes[j]==tmp)                    times++;                else                {                    currRes+=to_string(times);                                        currRes.push_back(tmp);                    tmp=preRes[j];                    times=1;                }            }            currRes+=to_string(times);                        currRes.push_back(tmp);            preRes=currRes;            currRes="";        }        return preRes;    }};


0 0