1
+ /* eslint-disable max-len */
2
+ /* eslint-disable no-restricted-syntax */
1
3
/* eslint-disable no-plusplus */
2
4
/*
3
5
Implemented by watching this conceptually video: https://www.youtube.com/watch?v=VA9m_l6LpwI
@@ -17,6 +19,7 @@ If found then return the index, else return -1
17
19
18
20
*/
19
21
22
+ const alphabets = 'abcdefghijklmnopqrstuvwxyz' ;
20
23
class Node {
21
24
constructor ( value , isEnd , index ) {
22
25
this . data = value ;
@@ -41,7 +44,12 @@ class SuffixTree {
41
44
let currentNode = this . head ;
42
45
while ( j < currentString . length ) {
43
46
if ( ! currentNode . next . has ( currentString [ j ] ) ) {
44
- currentNode . next . set ( currentString [ j ] , new Node ( currentString , true , i ) ) ;
47
+ let nextString = '' ;
48
+ while ( j < currentString . length ) {
49
+ nextString += currentString [ j ] ;
50
+ j ++ ;
51
+ }
52
+ currentNode . next . set ( nextString [ 0 ] , new Node ( nextString , true , i ) ) ;
45
53
break ;
46
54
} else {
47
55
let k = 0 ;
@@ -60,9 +68,20 @@ class SuffixTree {
60
68
diffString += partialMatchString [ k ] ;
61
69
k ++ ;
62
70
}
71
+
63
72
partialMatchNode . data = matchString ;
64
73
if ( diffString ) {
65
- partialMatchNode . next . set ( diffString [ 0 ] , new Node ( diffString , true , partialMatchNode . index ) ) ;
74
+ const oldMap = partialMatchNode . next ;
75
+ const newNode = new Node ( diffString , partialMatchNode . isEnd , partialMatchNode . index ) ;
76
+ const alphabetsArray = alphabets . split ( '' ) ;
77
+
78
+ for ( const char of alphabetsArray ) {
79
+ if ( oldMap . has ( char ) ) {
80
+ newNode . next . set ( char , oldMap . get ( char ) ) ;
81
+ }
82
+ }
83
+ partialMatchNode . next = new Map ( ) ;
84
+ partialMatchNode . next . set ( diffString [ 0 ] , newNode ) ;
66
85
partialMatchNode . isEnd = false ;
67
86
partialMatchNode . index = null ;
68
87
}
@@ -112,10 +131,17 @@ class SuffixTree {
112
131
}
113
132
}
114
133
115
- // const s = new SuffixTree('banana');
134
+ // const st = 'asdjkxhcjbzdmnsjakdhasdbajw';
135
+ // const s = new SuffixTree(st);
116
136
// s.constructSuffixTree();
137
+ // // console.log(s.head.next);
117
138
118
- // console.log(s.findSubstring('nana'));
119
139
140
+ // for (let i = 0; i < st.length; i++) {
141
+ // const e = st.substring(i);
142
+ // if (s.findSubstring(e) !== i) {
143
+ // console.log(e, i, s.findSubstring(e));
144
+ // }
145
+ // }
120
146
121
147
module . exports = SuffixTree ;
0 commit comments