记一次RK算法


public class RK {
	
	public static int rabinKarp(String str, String pattern){
		int m = str.length();
		int n = pattern.length();
		
		int patternCode = hash(pattern);
		int strCode = hash(str.substring(0,n));
		
		for(int i = 0;i<m-n+1;i++){
			if(strCode == patternCode && compareString(i, str, pattern)){
				return i;
			}
			
			if(i < m-n){
				strCode = nextHash(str, strCode, i, n);
			}
		}
		
		return -1;
	}
	
	public static int hash(String str){
		int hashcode  = 0;
		for(int i = 0 ; i<str.length() ; i++){
			hashcode += str.charAt(i)-'a';
		}
		return hashcode ;
	}
	
	public static int nextHash(String str, int hash, int index, int n){
		hash -= str.charAt(index)-'a';
		hash += str.charAt(index+n)-'a';
		return hash; 
	};
	
	private static boolean compareString(int i, String str, String pattern){
		String s = str.substring(i,i+pattern.length());
		return s.equals(pattern);
	}
	public static void main(String[] args) {
		String str = "aacdesadsdfer";
		String pattern  = "adsd";
		System.out.println(rabinKarp(str, pattern));
	}
	
}

 

发布了47 篇原创文章 · 获赞 13 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览