题目:
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,则判断B是否为A的子串,如果是,则返回1
- 如果A的长度大于B,但小于二倍B,B是A循环的子串,则返回2
- 如果A的长度小于B,则B如果可以成为A的N倍重复,则B = S0 + A * k + SE,其中(1)k至少为1,(2)S0 满足/A[-m0:]$/,(3)SE满足/^A[:me]/,字符串split函数可以将重复出现的A * k变为 '' * (k - 1),如果B还同时满足(2)、(3),则A的重复次数为split字符串分割后列表长度 + 1(因为有一个A作为分隔符,未出现在列表中)
代码:
class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
ret = 0
if A.find(B) > -1:
return 1
if (A * 2).find(B) > -1:
return 2
if B.find(A) < 0:
return -1
else:
splitB = B.split(A)
# print splitB
if ''.join(splitB[1:-1]) == '':
if splitB[0] != '' and A[::-1].find(splitB[0][::-1]) != 0:
return -1
if splitB[-1] != '' and A.find(splitB[-1]) != 0:
return -1
else:
return -1
ret = len(splitB) + 1
if splitB[0] == '':
ret -= 1
if splitB[-1] == '':
ret -= 1
return ret
思考:
以上代码在leetcode提交显示由于93%,虽然分析中3的情形可以通过直接计算字符串长度,生成A 的 N次重复,判断B是否在其中,但空间占用会大于以上代码。