用滚动哈希值(指利用之前的值),找字符串匹配

package demo2;

public class P81 {
//用滚动哈希值(指利用之前的值),找字符串匹配
	public static void main(String[] args) {
		String s="abcbbcabc";		//依次为主串、模式串
		String p="bc";
		long[] sHash=hashValue(s,p.length());
		long[] pHash=hashValue(p,p.length());
		hashMatch(sHash,pHash[0]);
	}

	static long[] hashValue(String str, int pLen) {
		int seed=7;		//哈希值,指字符串看作seed进制数字的值
		long[] res=new long[str.length()-pLen+1];
		int i=0;
		long hash=0;
		for(;i<pLen;i++) {
			hash=hash*seed+str.charAt(i);		
		}
		res[0]=hash;		//第一个靠扫描,之后滚动来求
		
		for(i=pLen;i<str.length();i++) {		//i为最新的一位
			char oldChar=str.charAt(i-pLen);
			//增加新的一位后去掉最早的一位
			hash= hash*seed+str.charAt(i) - oldChar*(long)Math.pow(seed, pLen);
			res[i-pLen+1]=hash;
		}
		
		return res;
	}
	
	static void hashMatch(long[] sHash, long pValue) {
		for(int i=0;i<sHash.length;i++) {
			if(pValue==sHash[i])
				System.out.println("match at : "+i);
		}
	}
	
}
posted @ 2022-05-05 17:38  fighterk  阅读(87)  评论(0)    收藏  举报