leetcode 481. magical string

本文解析了一种特殊的魔法字符串,该字符串由1和2组成,并遵循特定的生成规则。文章提供了通过编程方式计算前N个字符中1的数量的方法。

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

题目描述

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.
Example 1:
Input: 6
Output: 3
Explanation: The first 6 elements of magical string S is “12211” and it contains three 1’s, so return 3.

思路分析

说实话这道题不知道怎么整理,其实就是找规律类型的题目吧,关于这道题的大概意思就是字符串中1,2的连续个数形成的新字符串刚好是这个字符串的前面部分。也就是说这个字符串本身是可以生成的。从这个角度来看,我们可以从生成的字符串出发,去探讨这个字符串的产生过程,先设定字符串的初始值1,2,2 如果按1,2,2的模式去生成,那么下一个数字一定是1,而且是重复的两个1,在重复的两个1之后一定是一个2(相同数字最多出现两次,根据要生成的字符个数确定是1个2),同样可以推断出下一个数是一个1,由此,我们可以整理出一个大概的思路,我们首先对数字出现的次数寻找规律,我们可以设置一个指针作为次数指针,这个指针在数字生成的循环中起作用,我们同样需要一个尾指针,指向正在生成的元素。对于数字本身,我们知道1和2是交替出现的,因此用一个与3的异或即可,主要代码如下(注意初始化的过程):

int magicalString(int n) {
        if(n<=0) return 0;
        if(n<=3) return 1;
        vector<int> genVec(n+1);
        genVec[0] = 1;genVec[1] = 2;genVec[2] = 2;
        int head = 2,tail = 3;
        int num = 1,result = 1;
        while(tail<n) {
            for(int i = 0;i<genVec[head];i++) {
                genVec[tail] = num;
                if (num == 1 && tail < n) result++;
                tail++;
            }
            num=num^3;
            head++;
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值