题目
?
暴力解法
运用 StringBuilder 和 indexOf 来解决问题 StringBuilder 用来 存储存储 字符串 a 的叠加结果。 indexOf 用来 检查 字符串 a 重叠后 的 结果里 是否包含 子串 b。
?
代码
class Solution {
public int repeatedStringMatch(String a, String b) {
StringBuilder sb = new StringBuilder();
int result = 0;
while(sb.length() < b.length() && ++result>0 ){
sb.append(a);
}
sb.append(a);
int index = sb.indexOf(b);
if(index == -1){
return -1;
}
return index + b.length() > a.length()* result ? result+1 : result;
}
}
附图
?
class Solution {
public int repeatedStringMatch(String a, String b) {
StringBuilder sb = new StringBuilder();
int result = 0;
while(sb.length() < b.length() && ++result > 0){
sb.append(a);
}
sb.append(a);
int index = KMP(sb.toString(),b,0);
if(index == -1){
return -1;
}
return index + b.length() > a.length()*result ? result+1 : result;
}
public static int KMP(String str,String sub,int pos){
if(str == null || sub == null){
return -1;
}
if(str.length() == 0 || sub.length() == 0){
return -1;
}
int strLen = str.length();
int subLen = sub.length();
if(pos<0 || pos >= strLen){
return -1;
}
int i = pos;
int j = 0;
int[] next = new int[subLen];
getNext(sub,next);
while( i < strLen && j < subLen){
if(j == -1 || str.charAt(i) == sub.charAt(j)){
i++;
j++;
}else{
j = next[j];
}
}
if(j >= subLen){
return i-j;
}
return -1;
}
public static void getNext(String sub, int[] next){
next[0] = -1;
int k = -1;
int j = 1;
while( j < sub.length()){
if(k == -1 || sub.charAt(j-1) == sub.charAt(k)){
next[j] = k+1;
k++;
j++;
}else{
k = next[k];
}
}
}
}
|