加载中...
1668-最大重复子字符串(Maximum Repeating Substring)
发表于:2021-12-03 | 分类: 简单
字数统计: 385 | 阅读时长: 1分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/maximum-repeating-substring

英文原文

For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.

Given strings sequence and word, return the maximum k-repeating value of word in sequence.

 

Example 1:

Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in "ababc".

Example 2:

Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".

Example 3:

Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc". 

 

Constraints:

  • 1 <= sequence.length <= 100
  • 1 <= word.length <= 100
  • sequence and word contains only lowercase English letters.

中文题目

给你一个字符串 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" 的子字符串。

 

提示:

  • 1 <= sequence.length <= 100
  • 1 <= word.length <= 100
  • sequence 和 word 都只包含小写英文字母。

通过代码

高赞题解

解题思路

注意题目描述的是连续重复。
所以我们用StringBuilder拼接word
首先判断sequence是否包含word
如果包含则count++,然后sb再拼接一个word。
直至不包含为止退出循环。
count既是结果

image.png

代码

class Solution {
    public int maxRepeating(String sequence, String word) {
        int count = 0;
        StringBuilder sb = new StringBuilder(word);
        while(sequence.contains(sb)) {
            count++;
            sb.append(word);
        }
        return count;
    }
}

统计信息

通过次数 提交次数 AC比率
7363 16597 44.4%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1642-可以到达的最远建筑(Furthest Building You Can Reach)
下一篇:
1669-合并两个链表(Merge In Between Linked Lists)
本文目录
本文目录