public class RandomPatternMatch {
public RandomPatternMatch(){
}
public static int rPatternMatch(String x, String y){
//求出x0Int
int x0Int = 0;
for(int i=0;i<y.length();i++){
x0Int = x0Int + Integer.parseInt(x.substring(i, i+1))*(int)(Math.pow(2, y.length()-i-1));
}
//求出yInt
int yInt = 0;
for(int i=0;i<y.length();i++){
yInt = yInt + Integer.parseInt(y.substring(i, i+1))*(int)(Math.pow(2, y.length()-i-1));
}
int p = GenerateSuShu.suShu(0, 100); //随机产生一个素数p
int yIntModP = yInt % p; //求得y的指纹
int x0IntModP = x0Int % p;
if(x0IntModP == yIntModP){
//问题转换为对已经两个串的指纹相等,确定两个串是佛相等 即比较两个字符串是否相等
CompareLongStrings compareLongStrings = new CompareLongStrings();
boolean bool = compareLongStrings.CLongStrings(x.substring(0, y.length()-1), y);
if(bool == true)
return 0;
}
int xiInt = x0Int;
if(x0IntModP != yIntModP){
//移动模式
for(int i=1;i<x.length()-y.length()+1;i++){
xiInt = 2*xiInt - Integer.parseInt(x.substring(i-1, i))*(int)(Math.pow(2, y.length())) + Integer.parseInt(x.substring(i-1+y.length(), i-1+y.length()+1));
int xiIntModP = xiInt % p;
if(xiIntModP != yIntModP){
continue;
}
else{
CompareLongStrings compareLongStrings = new CompareLongStrings();
boolean bool = compareLongStrings.CLongStrings(x.substring(i, i+y.length()), y);
if(bool == true)
return i;
}
}
}
return 0;
}
}
有关如何比较两个字符串是否相等,利用随机化的思想进行优化见上一篇博文。