记一次RK算法

China☆狼群 提交于 2020-01-15 11:38:16

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));
	}
	
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!