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

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 @   fighterk  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示