Count and Say

来源:互联网 发布:练字软件app 编辑:程序博客网 时间:2024/06/07 13:20

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.

一个count-and-say序列就是一个如下的证书序列:

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

1 应该读成 "一个1" 或者 11.
11 应该被读成 "两个1" 或者 21.
21 应该被读成 "一个2, 然后 一个1" 或者 1211.

从第一个字符开始计算,设定一个变量cur,和当前字符比较,如果相同则count++,不同则令cur=当前字符。代码如下:

class Solution {    string Count(string s)    {        string sss;        string result="";        int count=0;        char cur=s[0];        for(int i=0;i<=s.size();i++)        {            if(cur==s[i]) count++;            else            {                stringstream ss;                ss<<count;                ss>>sss;                result+=sss;                string num;                num=cur;                result+=num;                //ss<<count<<cur;                count=1;                cur=s[i];            }        }        return result;    }public:    string countAndSay(int n) {        string s="1";        for(int i=1;i<n;i++)        {            s=Count(s);        }        return s;    }};


0 0