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.

思路:这道题主要是通过1这个数字产生,得出11,然后21,再然后1211。。。。就是通过上一个字符串中有几个1几个2等等,产生出下一个字符串。每一次对一个字符串循环计数,首先设置一个初始变量,计算第一个数字出现了几次,cont++;如果不等于,在开始将原有字符串中+count+上一次数字,将这个字符赋值给这个变量,count初始化为1,进行下次循环。就可以得到这个字符串应有的结果。

class Solution {
public:
    string countSay(const string &str)
    {
        string result;
        char temp=str[0];
        int count=1;
        int n=str.size();
        char count_ch;
        for(int i=1;i<n;i++)
        {
            if(str[i]==temp)
            {
                count++;
            }
            else
            {
                count_ch=count+'0';
                result=result+count_ch+temp;
                temp=str[i];
                count=1;
            }
        }
        count_ch=count+'0';
        result=result+count_ch+temp;
        return result;
    }
    string countAndSay(int n) {
        string say="1";
        for(int i=1;i<n;i++)
        {
            say=countSay(say);
        }
        return say;
    }
};

 

posted @ 2014-04-22 17:46  Awy  阅读(198)  评论(0编辑  收藏  举报