forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKMP.js
95 lines (87 loc) · 2.44 KB
/
KMP.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Function to create Longest Proper Prefix for given pattern that we want to search in the text*/
function lpsValues( lps, pattern, len_pattern)
{
//length of longest prefix that is also suffix, will be zero for 1st charater as no prefix ans no suffix
lps[0] = 0;
//length of previous longest prefix that is also suffix
var len_prev = 0;
//iterator to calculate values lps[1].....lps[len_pattern]
var i = 1;
while (i < len_pattern )
{
if (pattern.charAt(i) === pattern.charAt( len_prev))
{
len_prev = len_prev+1;;
lps[i] = len_prev;
i++;
}
else // (pat[i] != pat[len])
{
if (len_prev != 0)
{
len_prev = lps[len_prev - 1];
}
else // if (len == 0) as no prefix found
{
lps[i] = 0;
i++;
}
}
}
}
function KmpPatternSearch(pattern, text)
{
len_pattern = pattern.length;
len_text = text.length;
//We find Longest Proper Prefix to decide which chater will be matched next
var lps = new Array(len_pattern);
lpsValues(lps, pattern, len_pattern);
//iterator
var i = j = 0;
while (i < len_text)
{
if (pattern.charAt(j) === text.charAt(i))
{
//Pattern ans text matched
i = i+1;
j = j+1;
}
if (j === len_pattern)
{
return i-j;
j = lps[j-1];
}
else if (j != len_pattern && pattern.charAt(j) != text.charAt(i))
{
if (j != 0)
{
j = lps[j-1];
}
else
{
i = i+1;
}
}
}
}
//Used synchronous readline package to take console input
var readlineSync = require('readline-sync');
//User input for text to be searched
var a = readlineSync.question('Enter text to be searched: ');
//User input for pattern to be searched in text
var b = readlineSync.question('Enter the pattern to be searched: ');
var index=KmpPatternSearch(b,a);
if (index == undefined)
{
console.log("Pattern not found.");
}
else
{
console.log("Pattern observed at index:", index);
}
//Input 1: text :"abcabaabcabac" pattern:"abaa"
//Output will be 3
//Input 2: text:"aabbcdefgh" pattern:"fgh"
//Output will be 7
//Input 3: text:"aaaaaa" pattern:"bb"
//Output: Pattern not found