Skip to content

Commit e7d22b4

Browse files
committedAug 9, 2018
Use '===' for double check string comparision in RabinKarp.
1 parent d303d83 commit e7d22b4

File tree

1 file changed

+3
-26
lines changed

1 file changed

+3
-26
lines changed
 

‎src/algorithms/string/rabin-karp/rabinKarp.js

+3-26
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,5 @@
11
import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash';
22

3-
/**
4-
* Checks if two strings are equal.
5-
*
6-
* We may simply compare (string1 === string2) but for the
7-
* purpose of analyzing algorithm time complexity let's do
8-
* it character by character.
9-
*
10-
* @param {string} string1
11-
* @param {string} string2
12-
*/
13-
function stringsAreEqual(string1, string2) {
14-
if (string1.length !== string2.length) {
15-
return false;
16-
}
17-
18-
for (let charIndex = 0; charIndex < string1.length; charIndex += 1) {
19-
if (string1[charIndex] !== string2[charIndex]) {
20-
return false;
21-
}
22-
}
23-
24-
return true;
25-
}
26-
273
/**
284
* @param {string} text - Text that may contain the searchable word.
295
* @param {string} word - Word that is being searched in text.
@@ -52,10 +28,11 @@ export default function rabinKarp(text, word) {
5228
prevFrame = currentFrame;
5329

5430
// Compare the hash of current substring and seeking string.
55-
// In case if hashes match let's check substring char by char.
31+
// In case if hashes match let's make sure that substrings are equal.
32+
// In case of hash collision the strings may not be equal.
5633
if (
5734
wordHash === currentFrameHash
58-
&& stringsAreEqual(text.substr(charIndex, word.length), word)
35+
&& text.substr(charIndex, word.length) === word
5936
) {
6037
return charIndex;
6138
}

0 commit comments

Comments
 (0)
Please sign in to comment.