|
1 | 1 | import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash'; |
2 | 2 |
|
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 | | - |
27 | 3 | /** |
28 | 4 | * @param {string} text - Text that may contain the searchable word. |
29 | 5 | * @param {string} word - Word that is being searched in text. |
@@ -52,10 +28,11 @@ export default function rabinKarp(text, word) { |
52 | 28 | prevFrame = currentFrame; |
53 | 29 |
|
54 | 30 | // 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. |
56 | 33 | if ( |
57 | 34 | wordHash === currentFrameHash |
58 | | - && stringsAreEqual(text.substr(charIndex, word.length), word) |
| 35 | + && text.substr(charIndex, word.length) === word |
59 | 36 | ) { |
60 | 37 | return charIndex; |
61 | 38 | } |
|
0 commit comments