【LeetCode & 剑指offer刷题】字符串题16:Count and Say

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"

C++
 
/*
 问题:Count and say 产生第n个count and say序列
 aabbccd翻译为na a nb b nc c nd d,如:
 1.     1
 2.     11
 3.     21
 4.     1211
 5.     111221
 6.     312211
*/
//字符串保存结果
#include <string>
class Solution
{
public:
    string countAndSay(int n)
    {
        if(n <= 0) return ""; //返回空串
       
        string pre = "1"; //初始串为1
        while(--n) //产生第2~n的序列(产生后面n-1个序列)
        {
            string cur = ""; //用于缓存当前序列,初始化为空串
            for(int i = 0; i< pre.size(); i++ )//i = 0 ~ len-1,遍历整个串
            {
                int count = 1;
                while(i+1 < pre.size() && pre[i] == pre[i+1]) //统计连续相同数的个数(注意加上i+1<pre.size()的条件)
                {
                    count++;
                    i++;
                }
                cur += to_string(count) + pre[i]; //组合成字符串,如na a
           //     cout<<cur<<endl;
            }
            pre = cur; //传值给结果
        }
        return pre;
    }
};
 

 

posted @ 2019-01-05 16:10  wikiwen  阅读(121)  评论(0编辑  收藏  举报