This is the 24th day of my participation in the August Text Challenge.More challenges in August
describe
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".
Copy the code
Example 2:
Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".
Copy the code
Example 3:
Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc".
Copy the code
Note:
1 <= sequence.length <= 100
1 <= word.length <= 100
sequence and word contains only lowercase English letters.
Copy the code
parsing
Find the largest number of consecutive words in the string sequence. The idea is simple, that is, calculate the maximum number of consecutive splicing of word n, and then splice the word n times to determine whether it exists in the sequence. If not, determine whether n-1 exists in the sequence, and so on. If not, So I’m just going to return 0.
answer
class Solution(object):
def maxRepeating(self, sequence, word):
"""
:type sequence: str
:type word: str
:rtype: int
"""
L = len(sequence)
l = len(word)
n = L // l
for i in range(n, 0, -1):
if sequence.count(word * i):
return i
return 0
Copy the code
The results
Runtime: 16 ms, faster than 76.23% of Python online submissions for Maximum Repeating Substring. Memory Usage: Each node in the Python online submission list for Maximum Repeating Substring.Copy the code
parsing
Alternatively, you can use Python’s built-in function find to solve this problem. If word*n exists in the sequence, add one to the result. If word*n exists in the sequence, add one to the result. Otherwise, result is returned.
answer
class Solution(object): def maxRepeating(self, sequence, word): """ :type sequence: str :type word: str :rtype: int """ result = 0 count = len(sequence) // len(word) for n in range(1, count + 1): if sequence.find(word * n) ! = -1: result += 1 else: break return resultCopy the code
The results
Runtime: 8 ms, faster than 100.00% of Python online submissions for Maximum repeatsubstring. Memory Usage: 13.6 MB, less than 34.78% of Python online submissions for Maximum Repeating Substring.Copy the code
Original link: leetcode.com/problems/ma…
Your support is my biggest motivation