[leetcode-38]Count and Say

本文探讨了LeetCode上的两道题目:“CountandSay”与“魔法字符串”(Magic String)。通过分析题目要求和给出的示例代码,介绍了如何使用序列生成方法解决问题,并讨论了在实现过程中需要注意的关键细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自动生成序列的一道题,想起来昨天比赛里遇见的另一道题,问C_∞序列第N位是多少,昨天死磕到最后也就是写了个垃圾代码,然后输入N>10就不能运行,觉得这类题的要点是要开两个序列,一个生成另一个后,然后拷贝回来,然后记得往后推测的两个条件,

1.注意现有数列边界,不要越界,例如下面代码中的i+1<res.size()

2.注意题目限制推到第X位,例如Count and Say里要推到第N个序列,就有一个while(n--)的限制,昨天的垃圾代码里就有一个i<n的限制

然后上代码,先上Count and Say标程(题目没看懂直接看了标程...):

string countAndSay(int n) {
    if (n == 0) return "";
    string res = "1";
    while (--n) {
        string cur = "";
        for (int i = 0; i < res.size(); i++) {
            int count = 1;
             while ((i + 1 < res.size()) && (res[i] == res[i + 1])){
                count++;    
                i++;
            }
            cur += to_string(count) + res[i];
        }
        res = cur;
    }
    return res;
}
然后是昨天的题目[leetcode-481] Magic String

A magical string S consists of only '1' and '2' and obeys the following rules:

The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.

The first few elements of string S is the following: S = "1221121221221121122……"

If we group the consecutive '1's and '2's in S, it will be:

1 22 11 2 1 22 1 22 11 2 11 22 ......

and the occurrences of '1's or '2's in each group are:

1 2	2 1 1 2 1 2 2 1 2 2 ......

You can see that the occurrence sequence above is the S itself.

Given an integer N as input, return the number of '1's in the first N number in the magical string S.

Note: N will not exceed 100,000.
附垃圾代码供参考,题解稍后我改改再发:

int magicalString(int n) {
        int s[3125],k=2,countx=1,j,i,flag=0;
        //k代表递推出来的位置
        //countx代表第k位前1的个数
        //i,j代表正在从(32*j+i)递推
        s[0]=1;
        for(i=2,j=0;k<n;i++){
            if(i==32){
                i=0;j++;
            }
            if(s[j]&1<<i==1){           //当前连续序列长度为1时
                if(flag==1)             //当前序列当1时
                {
                    s[k/32]+=1<<k%32;
                    countx+=1;
                }
            }
            else{                       //当前连续序列长度为2时
                if(flag==1)             //当前序列应当添1时
                {
                    s[k/32]+=1<<k%32;
                    k++;
                    s[k/32]+=1<<k%32;
                    countx+=2;
                }
                else{
                    k+=1;
                }
            }
            k+=1;
            flag=1-flag;
        }
        cout<<s[0]<<endl;
        return countx;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值