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 ofA
and B
will be between 1 and 10000.
M1: brute force
keep string builder and appending until the length A is greater or equal to B
B要能成为A的字符串,那么A的长度肯定要大于等于B,所以当A的长度小于B的时候,先重复A,直到A的长度大于等于B,并且累计次数cnt。此时找B是否存在A中,如果存在直接返回cnt。如果不存在,加上一个A再找(这样可以处理这种情况A="abc", B="cab")如果此时还找不到,说明无法匹配,返回-1。时间:O(M+N),空间:O(max(M, N))
class Solution { public int repeatedStringMatch(String A, String B) { StringBuilder sb = new StringBuilder(); sb.append(A); int cnt = 1; while(sb.length() < B.length()) { sb.append(A); cnt++; } if(sb.toString().contains(B)) return cnt; else if(sb.append(A).toString().contains(B)) return cnt+1; else return -1; }}
M2: KMP
时间:O(N)