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

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;
	}
}
          有关如何比较两个字符串是否相等,利用随机化的思想进行优化见上一篇博文。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值