Skip to content

Commit

Permalink
Use '===' for double check string comparision in RabinKarp.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Aug 9, 2018
1 parent d303d83 commit e7d22b4
Showing 1 changed file with 3 additions and 26 deletions.
29 changes: 3 additions & 26 deletions src/algorithms/string/rabin-karp/rabinKarp.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,5 @@
import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash';

/**
* Checks if two strings are equal.
*
* We may simply compare (string1 === string2) but for the
* purpose of analyzing algorithm time complexity let's do
* it character by character.
*
* @param {string} string1
* @param {string} string2
*/
function stringsAreEqual(string1, string2) {
if (string1.length !== string2.length) {
return false;
}

for (let charIndex = 0; charIndex < string1.length; charIndex += 1) {
if (string1[charIndex] !== string2[charIndex]) {
return false;
}
}

return true;
}

/**
* @param {string} text - Text that may contain the searchable word.
* @param {string} word - Word that is being searched in text.
Expand Down Expand Up @@ -52,10 +28,11 @@ export default function rabinKarp(text, word) {
prevFrame = currentFrame;

// Compare the hash of current substring and seeking string.
// In case if hashes match let's check substring char by char.
// 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
&& stringsAreEqual(text.substr(charIndex, word.length), word)
&& text.substr(charIndex, word.length) === word
) {
return charIndex;
}
Expand Down

0 comments on commit e7d22b4

Please sign in to comment.