模式匹配(pattern matching)问题:判断一个长为n的字符串X中是否包含常为m的字串Y(m<=n)

来源:互联网 发布:android读取串口数据 编辑:程序博客网 时间:2024/05/09 04:03

public class RandomPatternMatch {public RandomPatternMatch(){}public static int rPatternMatch(String x, String y){//求出x0Intint 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));}//求出yIntint 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);          //随机产生一个素数pint 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;}}
          有关如何比较两个字符串是否相等,利用随机化的思想进行优化见上一篇博文。

原创粉丝点击