Count and Say 【leetcode】

来源:互联网 发布:jtl 文件java 解析 编辑:程序博客网 时间:2024/05/21 07:05

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.



两个变量去扫描字符串,temp表示当前的值,n表示当前的值的个数。

class Solution {public:    string countAndSay(int n) {        string a,b;        a="1";        for(int i=2;i<=n;++i)        {            b="";            int len=a.size(),n=1;            char temp=a[0];            for(int j=1;j<len;++j)            {                if(a[j]!=temp)                {                    b+='0'+n;                    b+=temp;                    temp=a[j];                    n=1;                }                else                    n++;                            }            b+='0'+n;            b+=temp;            swap(a,b);        }        return a;    }};


原创粉丝点击