leetcode-1668:最大重复子字符串

简介: leetcode-1668:最大重复子字符串

题目

题目连接

给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word 的 重复值为 k 。单词 word 的 最大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串,那么重复值 k 为 0 。

给你一个字符串 sequence 和 word ,请你返回 最大重复值 k 。

示例 1:

输入:sequence = "ababc", word = "ab"
输出:2
解释:"abab" 是 "ababc" 的子字符串。

示例 2:

输入:sequence = "ababc", word = "ba"
输出:1
解释:"ba" 是 "ababc" 的子字符串,但 "baba" 不是 "ababc" 的子字符串。

示例 3:

输入:sequence = "ababc", word = "ac"
输出:0
解释:"ac" 不是 "ababc" 的子字符串。

解题

方法一:字典树

class Trie{
public:
    vector<Trie*> next;
    bool isEnd;
    Trie(){
        next=vector<Trie*>(26,nullptr);
        isEnd=false;
    }
    void insert(string&& word){
        Trie* node=this;
        for(char c:word){
            if(node->next[c-'a']==nullptr){
                node->next[c-'a']=new Trie();
            }
            node=node->next[c-'a'];
        }
        node->isEnd=true;
    }
};
class Solution {
public:
    int maxRepeating(string sequence, string word) {
        int res=0;
        Trie* trie=new Trie();
        int n=sequence.size();
        //把所有情况都放入字典树查找
        for(int i=0;i<n;i++){
            trie->insert(sequence.substr(i,n-i));
        }
        //查看重复出现了几次
        Trie* node=trie;
        while(true){
            for(char c:word){
                if(node->next[c-'a']) node=node->next[c-'a'];
                else return res;
            }
            res++;
        }
        return res;
    }
};

方法二:序列DP

参考链接

dp[i]表示以 sequence索引i-1为结尾时的最大重复次数

class Solution {
public:
    int maxRepeating(string sequence, string word) {
        int n=sequence.size(),m=word.size();
        vector<int> dp(n+1,0);
        int res=0;
        for(int i=1;i<=n;i++){
            if(i>=m&&sequence.substr(i-m,m)==word) dp[i]=max(dp[i],dp[i-m]+1);
            res=max(res,dp[i]);
        }
        return res;
    }
};
相关文章
|
13天前
|
C++
Leetcode第43题(字符串相乘)
本篇介绍了一种用C++实现的字符串表示的非负整数相乘的方法,通过逆向编号字符串,将乘法运算转化为二维数组的累加过程,最后处理进位并转换为字符串结果,解决了两个大数相乘的问题。
21 9
|
13天前
|
算法 C++
Leetcode第八题(字符串转换整数(atoi))
这篇文章介绍了LeetCode上第8题“字符串转换整数(atoi)”的解题思路和C++的实现方法,包括处理前导空格、正负号、连续数字字符以及整数溢出的情况。
12 0
|
13天前
【LeetCode 22】459.重复的子字符串
【LeetCode 22】459.重复的子字符串
25 0
|
13天前
【LeetCode 20】151.反转字符串里的单词
【LeetCode 20】151.反转字符串里的单词
14 0
|
13天前
【LeetCode 19】541.反转字符串II
【LeetCode 19】541.反转字符串II
15 0
|
13天前
【LeetCode 18】6.2.反转字符串
【LeetCode 18】6.2.反转字符串
12 0
|
2月前
|
存储 算法
LeetCode第43题字符串相乘
LeetCode第43题"字符串相乘"的解题方法,通过使用数组存储乘积并处理进位,避免了字符串转换数字的复杂性,提高了算法效率。
LeetCode第43题字符串相乘
|
2月前
|
算法 Java
LeetCode第28题找出字符串中第一个匹配项的下标
这篇文章介绍了LeetCode第28题"找出字符串中第一个匹配项的下标"的两种解法:暴力解法和KMP算法,并解释了KMP算法通过构建前缀表来提高字符串搜索的效率。
LeetCode第28题找出字符串中第一个匹配项的下标
|
2月前
|
算法
LeetCode第8题字符串转换整数 (atoi)
该文章介绍了 LeetCode 第 8 题字符串转换整数 (atoi)的解法,需要对字符串进行格式解析与校验,去除前导空格和处理正负号,通过从高位到低位的计算方式将字符串转换为整数,并处理越界情况。同时总结了这几道题都需要对数字的表示有理解。
LeetCode第8题字符串转换整数 (atoi)
|
4月前
|
算法
力扣每日一题 6/23 字符串/模拟
力扣每日一题 6/23 字符串/模拟
39 1