686. superimposing repeatedly a string matching
Given two strings A and B, to find the minimum number of repetitions of the A string is superimposed, so that the string become substrings A B after the addition, if there is no or -1.
For example, A = "abcd", B = "cdabcdab".
Answer is 3, because of "abcdabcdabcd", case B is the superposition of the sub strings A repeated three times; the A string is repeated twice superimposed "abcdabcd", B is not its children.
note:
A and B string length in the range of 1 and 10,000 interval.
class Solution {
public int repeatedStringMatch(String A, String B) {
//滚轮? A作为滚轮
char[] a = A.toCharArray();
char[] b = B.toCharArray();
for(int i=0;i<a.length;i++){
int len = loop(a,b,i);
if(len > 0){//
int count = 1;
len = B.length() - a.length + i;
count += len/a.length;
count += len%a.length > 0 ? 1 : 0;
return count;
}else if(len + a.length <= 0){
return -1;
}
}
return -1;
}
//使用a滚轮印刷b,start为起始点
public int loop(char[] a,char[] b,int start){
int count = start;
for(char c : b){
if(a[start % a.length] != c){
return count - start;
}
start++;
}
return 1;
}
}