[LeetCode] 1668. 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 sequenceword'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 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-repeating-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意不难理解,问 word 最多可以重复多少次,依然是 sequence 的一个子串。word 的重复可以用 StringBuilder 进行拼接,检查子串可以用Java自带的 String.contains() 函数,但是注意时间复杂度会到 O(n^2)。

时间O(n^2)

空间O(n) - StringBuilder

Java实现

 1 class Solution {
 2     public int maxRepeating(String sequence, String word) {
 3         // corner case
 4         if (sequence.equals(word)) {
 5             return 1;
 6         }
 7 
 8         // normal case
 9         int m = sequence.length();
10         int n = word.length();
11         int max = m / n;
12         for (int k = max; k >= 1; k--) {
13             StringBuilder sb = new StringBuilder();
14             for (int i = 0; i < k; i++) {
15                 sb.append(word);
16             }
17             String sub = sb.toString();
18             if (sequence.contains(sub)) {
19                 return k;
20             }
21         }
22         return 0;
23     }
24 }

 

讨论区看到一个更简洁的代码。复杂度相同。

 1 class Solution {
 2     public int maxRepeating(String sequence, String word) {
 3         int count = 0;
 4         StringBuilder sb = new StringBuilder(word);
 5         while (sequence.contains(sb)) {
 6             count++;
 7             sb.append(word);
 8         }
 9         return count;
10     }
11 }

 

LeetCode 题目总结

posted @ 2022-11-03 15:00  CNoodle  阅读(112)  评论(0)    收藏  举报