[Leetcode] 466. Count The Repetitions 解题报告

这篇博客探讨了LeetCode的466题,涉及字符串处理和动态规划。作者提供了题目描述,并指出这是一道具有挑战性的题目,即使阅读了网上解法仍需深入理解。尽管没有给出详细解答,但作者承诺后续会补充解释。

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

题目

Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".

On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.

You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.

Example:

Input:
s1="acb", n1=4
s2="ab", n2=2

Return:
2

思路

一道比较变态的题目,看了网上的代码之后依然没有完全明白。先贴出来,随后等完全弄明白了再补充解释吧。

代码

class Solution {
public:
    int getMaxRepetitions(string s1, int n1, string s2, int n2) {
        vector<int> rapport(102, -1), rest(102, -1);
        int b = -1, posRest = 0, rap = 0;
        int last = -1;
        rapport[0] = rest[0] = 0;                   //case when n=0
        for(int i = 1; i <= s2.size() + 1; ++i) {
            int j;
            for(j = 0; j < s1.size(); ++j) {
                if(s2[posRest] == s1[j]) {
                    ++posRest;
                    if(posRest == s2.size()) {
                        ++rap;
                        posRest = 0;
                    }
                }
            }
            for(int k = 0; k < i; ++k) {
                if(posRest == rest[k]) {
                    b = k;
                    last = i;
                    break;
                }
            }
            rapport[i] = rap;
            rest[i] = posRest;
            if(b >= 0) {
                break;
            }
        }
        int interval = last - b;
        if(b >= n1) {
            return rapport[n1] / n2;
        }
        return ((n1 - b) / interval * (rapport[last] - rapport[b]) + rapport[(n1 - b )% interval + b]) / n2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值