Skip to content

Commit 2c5aaa3

Browse files
committedOct 30, 2020
Add KMP string searching algorithm
1 parent 2190b92 commit 2c5aaa3

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
 

Diff for: ‎String/KMPPatternSearching.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Implementing KMP Search Algorithm to search all the instances of pattern in
2+
// given text
3+
// Reference Book: Introduction to Algorithms, CLRS
4+
5+
// Explanation: https://www.topcoder.com/community/competitive-programming/tutorials/introduction-to-string-searching-algorithms/
6+
7+
const computeLPS = (pattern) => {
8+
const lps = Array(pattern.length)
9+
lps[0] = 0
10+
for (let i = 1; i < pattern.length; i++) {
11+
let matched = lps[i - 1]
12+
while (matched > 0 && pattern[i] !== pattern[matched]) {
13+
matched = lps[matched - 1]
14+
}
15+
if (pattern[i] === pattern[matched]) {
16+
matched++
17+
}
18+
lps[i] = matched
19+
}
20+
return lps
21+
}
22+
23+
/**
24+
* Returns all indices where pattern starts in text
25+
* @param {*} text a big text in which pattern string is to find
26+
* @param {*} pattern the string to find
27+
*/
28+
const KMPSearch = (text, pattern) => {
29+
if (!pattern || !text) {
30+
return [] // no results
31+
}
32+
33+
// lps[i] = length of proper prefix of pattern[0]...pattern[i-1]
34+
// which is also proper suffix of it
35+
const lps = computeLPS(pattern)
36+
const result = []
37+
38+
let matched = 0
39+
for (let i = 0; i < text.length; i++) {
40+
while (matched > 0 && text[i] !== pattern[matched]) {
41+
matched = lps[matched - 1]
42+
}
43+
if (text[i] === pattern[matched]) {
44+
matched++
45+
}
46+
if (matched === pattern.length) {
47+
result.push(i - pattern.length + 1)
48+
matched = lps[matched - 1]
49+
}
50+
}
51+
52+
return result
53+
}
54+
55+
export { KMPSearch }

Diff for: ‎String/test/KMPPatternSearching.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { KMPSearch } from '../KMPPatternSearching'
2+
3+
describe('KMP Matcher', () => {
4+
it('TC1: expects to return matching indices for pattern in text', () => {
5+
const text = 'ABC ABCDAB ABCDABCDABDE'
6+
const pattern = 'ABCDABD'
7+
expect(KMPSearch(text, pattern)).toStrictEqual([15])
8+
})
9+
10+
it('TC2: expects to return matching indices for pattern in text', () => {
11+
const text = 'ABC ABCDABD ABCDABCDABDE'
12+
const pattern = 'ABCDABD'
13+
expect(KMPSearch(text, pattern)).toStrictEqual([4, 16])
14+
})
15+
})

0 commit comments

Comments
 (0)
Please sign in to comment.