Leetcode481. 魔力字符串

Leetcode481. Magical 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.

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放在一起形成分组,其分组构成的字符串正好是它本身。
我们先从简单的开始分析,比如12211,单独的一个1就是一个分组,两个连续的2构成一个分组,两个连续的1构成一个分组,可以看到这三个分组连成起来的字符串刚好就是122,与原字符串前缀相同。
题目要求我们给定任意的一个数字n,找出魔力字符串前n位中1的个数。思路很明确,只要我们构造出了魔力字符串,问题就顺利解决了。那么我们应该怎样进行构造呢?

我们新建一个数组,并将数组的前3个元素初始化为122,那么此时1的个数count就为1。接下来我们用两个指针head和tail,前者指示将要被生成新数字的次数,后者指示下一个要放新数字的空位置。由于122对应的分组字符串为12,因此head应该初始化为2,tail应该初始化为3。
当tail小于n时,就不断构造魔力字符串;由于head指向的数字代表要生成的新数字的个数,因此可将其当作一个循环的临界判别条件。在生成新数字的过程中,同时注意判断生成的数字是否为1,如果为1,则count++;直到tail等于n为止。
注意到魔力字符串是由1和2交替构成的,这里用到了一个小tip:1^3=2,2^3=1,这里也可以用if语句进行代替。

源代码

class Solution {
public:
    int magicalString(int n) {
        if (n == 0) {
            return 0;
        }
        if (n >= 1 && n <= 3) {
            return 1;
        }
        int count = 1, num = 1, head = 2, tail = 3;
        int* arr = new int[n + 1];
        arr[0] = 1;
        arr[1] = arr[2] = 2;
        while (tail < n) {
            for (int i = 0; i < arr[head]; i++) {
                arr[tail] = num;
                if (tail < n && num == 1) {
                    count++;
                }
                tail++;
            }
            num = num ^ 3;
            head++;
        }
        return count;
    }
};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值