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

【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   n th   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 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值