题目描述:
LeetCode 686. Repeated String Match
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").
Note:
The length of A
and B
will be between 1 and 10000.
题目大意:
给定字符串A和B,求A至少重复几次,才能包含B。若不存在,返回-1。
解题思路:
蛮力法
Python代码:
class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
sa, sb = len(A), len(B)
x = 1
while (x - 1) * sa <= 2 * max(sa, sb):
if B in A * x: return x
x += 1
return -1
本文链接:http://bookshadow.com/weblog/2017/10/01/leetcode-repeated-string-match/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
Shane Tsui 发布于 2018年4月22日 20:55 #
The solution is incorrect for this test case:
"abcbc"
"cabcbca"
在线疯狂 发布于 2018年4月23日 20:15 #
Thank you for your reminder! :)
I have modified the code accordingly.