编辑代码

public class HelloWorld {
    public static void main(String []args) {
	   String Str = new String("在我这里面需要查找查找的串需要查找的串");
	   String Str2 = new String("需要查找的串");
	   System.out.println("查找到的位置在第 "+rK(Str,Str2)+" 个");
    }

    // 原始模板
    public static int rK(String a,String b) {
		int m=a.length(),n=b.length(),s,j;
        
		int[] hash=new int[m-n+1];
		int[] table=new int[26];
		char[] a1=a.toCharArray();
		char[] b1=b.toCharArray();
		s=1;
		//将26的次方存储在一个表里,取的时候直接用,虽然溢出,但没啥问题
		for(j=0;j<26;j++) {
			table[j]=s;
			s*=26;
		}
		for(int i=0;i<=m-n;i++) {
			s=0;
			for(j=0;j<n;j++) {
                int in = n-1-j;
                // -- -'a' 这个好像是多余的
				// s+=(a1[i+j]-'a')*table[n-1-j]; 
                s+=(a1[i+j])*table[n-1-j]; 
			}
			hash[i]=s;
		}
		s=0;
		for(j=0;j<n;j++) {
            // -'a' 这个好像是多余的
			// s+=(b1[j]-'a')*table[n-1-j];
            s+=(b1[j])*table[n-1-j];
		}
		for(j=0;j<m-n+1;j++) {
			if(hash[j]==s) {
				return j;
			}
		}
		return -1;
	}
}