代码拉取完成,页面将自动刷新
同步操作将从 Gitee 极速下载/javascript-algorithms 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash';
/**
* @param {string} text - Text that may contain the searchable word.
* @param {string} word - Word that is being searched in text.
* @return {number} - Position of the word in text.
*/
export default function rabinKarp(text, word) {
const hasher = new PolynomialHash();
// Calculate word hash that we will use for comparison with other substring hashes.
const wordHash = hasher.hash(word);
let prevFrame = null;
let currentFrameHash = null;
// Go through all substring of the text that may match.
for (let charIndex = 0; charIndex <= (text.length - word.length); charIndex += 1) {
const currentFrame = text.substring(charIndex, charIndex + word.length);
// Calculate the hash of current substring.
if (currentFrameHash === null) {
currentFrameHash = hasher.hash(currentFrame);
} else {
currentFrameHash = hasher.roll(currentFrameHash, prevFrame, currentFrame);
}
prevFrame = currentFrame;
// Compare the hash of current substring and seeking string.
// In case if hashes match let's make sure that substrings are equal.
// In case of hash collision the strings may not be equal.
if (
wordHash === currentFrameHash
&& text.substr(charIndex, word.length) === word
) {
return charIndex;
}
}
return -1;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。