Description:
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.
Solution:
Initial Attempt: Failed due to TIME OUT EXCEPTION
Apparantly , if String B is very long, and A is extremely short, the repeat times is almost the same length as String B. Thus, would cause timeout exception.
class Solution { public int repeatedStringMatch(String A, String B) { if(A==null||A.length()==0){ return -1; } int times = B.length() / A.length()+ 2; // System.out.println(Repeat(A,3).indexOf(B)); for(int i = 1; i<= times; i++){ if(Repeat(A,i).indexOf(B)>-1){ return i; } } return -1; } static String Repeat (String a, int b){ String result = a; for(int i = 1; i<b; i++){ result = result + a; } return result; } }
Second Attempt
class Solution { public int repeatedStringMatch(String A, String B) { if(A==null||A.length()==0){ return -1; } StringBuffer sb = new StringBuffer(A); int count = 1; while(sb.indexOf(B)==-1){ if(sb.length()>A.length()+B.length()){ return -1; } sb = sb.insert(0,A); count++; } return count; } }