LeetCode算法题之Count and Say

//问题描述
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,则输出他的第N个变形,其实这更具灵活性

class Solution
{
public:
    string countAndSay(int n)
    {
        if(n<=0)
            return "";
        if(n == 1)
            return "1";
        int sequenceLength = n-2;//此处很诡异啊,要是不减去2,下面的while循环会多循环2次,实际上很好理解,sequence是辗转调用的
        stringstream itos;
        itos<<n;
        string sequence = "1" + itos.str(); //将数字转为字符串

        while(sequenceLength >0)
        {   //反复调用
            sequence = printSequence(sequence);
            sequenceLength--;
        }
        return sequence;
    }
    string printSequence(string str)
    {
        string tempString;

        unsigned int i=0;
        int index=0;
        unsigned int j=0;
        while(j<str.length())
        {
            if(str[i] == str[j])
            {
                index++;
                if(j+1 == str.length())
                {  //最后一个数字的比较,下面的else语句将不再执行,只能在此处执行,否则将会把它漏掉
                    tempString = tempString + (char)(index+'0') +(char)str[i];
                    break;
                }
            }
            else
            {
                tempString = tempString + (char)(index+'0') +(char)str[i];
                i = j;//从下一个不同处开始计算某个数的连续存在次数,比如112211,数字1连续存在两次后,
		      //变成2,此处的str[i]将变成2开始往下统计2的连续存在次数
                j--;  //j一定要退回一格,保持str[i]将变成2的同时str[j]还是2
                index = 0;
            }
            j++;
        }
        return tempString;
    }
};
//只是对1这个数而言,输入一个整数n,输出1的第n次变形,不过没关系,用下面的
//代码将上面理解错误的代码中第一个while循环前的代码替换掉即可AC

if(n<0)
    return "";
if(n == 1)
    return "1";
int sequenceLength = n-2;
string sequence = "11" ;

网上其他大神写的比我的简洁的多,没办法,笨啊!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值