首页 > 其他 > 详细

Count and Say

时间:2014-04-23 00:28:06      阅读:442      评论:0      收藏:0      [点我收藏+]

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,进行下次循环。就可以得到这个字符串应有的结果。

bubuko.com,布布扣
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;
    }
};
bubuko.com,布布扣

 

Count and Say,布布扣,bubuko.com

Count and Say

原文:http://www.cnblogs.com/awy-blog/p/3681061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!