Rabin-Karp指纹字符串查找
基本思想是所有字符串都可以看成R进制的数字;
对于100位的字符串就没法办法直接取余了,因为int只能存10位,long最多也只能存19位数;
关键思想是可以根据 i 高效的算出 i+1 的哈希值,这是由取余的分配律决定的;
txtHash = (txtHash-RM*txt.charAt(i) % Q +Q
long patHash = 0;
long txtHash = 0;
for(int j = 0;j < M; j++){
patHash = (R*h + pat.charAt(j))%Q;
txtHash = (R*h + txt.charAt(j))%Q;
}
if(txtHash == patHash) return 0;
for(int i = 0; i<txt.length()-M; i++){
txtHash = (txtHash-RM*txt.charAt(i) % Q + Q) % Q;
txtHash = (txtHash*R+txt.charAt(i+M))%Q;
if(patHash == txtHash)
return i+1;
}
return -1;
字节跳动变量名拆分
输入样例
thisisadog
this thisis is a dog
输出样例
True
Java的indexOf()实现
Scanner in = new Scanner(System.in);
String txt = in.next();
String pat;
boolean result = true;
while(in.hasNext()){
pat = in.next();
if(txt.indexOf(pat)==-1){
result = false;break;
}
}
System.out.print(result);