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的子串
C++(16ms):
1 class Solution { 2 public: 3 int repeatedStringMatch(string A, string B) { 4 string t = A ; 5 for(int i = 1 ; i <= B.length()/A.length()+2 ; i++){ 6 if (t.find(B) != string::npos){ 7 return i ; 8 }else{ 9 t += A ; 10 } 11 } 12 return -1; 13 } 14 };
Java(412ms):
1 class Solution { 2 public int repeatedStringMatch(String A, String B) { 3 String t = A ; 4 for(int i = 1 ; i <= B.length()/A.length()+2 ; i++){ 5 if (t.indexOf(B) != -1) 6 return i ; 7 else 8 t += A ; 9 } 10 return -1 ; 11 } 12 }