LeetCode 38. Count and Say

来源:互联网 发布:扫码收款软件 编辑:程序博客网 时间:2024/05/22 19:42

问题描述:

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.


题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,
因为上次字符串有1个1,所以输出11;
n=3时,由于上次字符是11,有2个1,所以输出21;
n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
依次类推

解题思路:
从第一个字符串’1‘,开始,依次寻找其下一个串,直到找到所需要的第N个字符串序列为止。

所以题目重点就在于getNext(string s)的实现

实现getNext(string s)函数的时候,要注意遍历当前的s字符串时,,在当前位置,计算字符连续为pre的个数,每次判断相同的时候,count++,不同的时候,在结果字符串中对当前的字符串部分先表示了,然后顺序向下遍历,同时更新pre和count的值。

AC代码:

string getNext(string s){    //保存最终的结果    string res;    char pre = s[0];    int count = 1;    //从字符串的第二个元素开始循环判断,与其前一个元素比较    for(int i = 1;i < s.size();i++)    {        if(s[i] == pre)        {            count++;        }        else        {            //temp即为连续字符为pre的个数(加'0'变为字符)            char temp = count + '0';            res = res + temp + pre;            pre = s[i];            count = 1;        }    }    char temp = count + '0';    res = res + temp + pre;    return res;}string countAndSay(int n){    string s = "1";    while(--n)    {        s = getNext(s);    }    return s;}


0 0
原创粉丝点击