File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ class Trie {
2+ constructor ( ) {
3+ this . word = null
4+ this . children = new Array ( 27 )
5+ this . cnt = 0
6+ }
7+ }
8+ /**
9+ * @param {string[] } words
10+ * @return {number }
11+ */
12+ var countPrefixSuffixPairs = function ( words ) {
13+ const M = 31
14+ let rt1 = new Trie ( )
15+ let rt2 = new Trie ( )
16+ let res = 0
17+
18+ for ( let w of words ) {
19+ res += addAndCount ( w )
20+ }
21+
22+ return res
23+
24+ function addAndCount ( w ) {
25+ let res = 0
26+ let pre = rt1
27+ let suf = rt2
28+ let n = w . length
29+
30+ for ( let i = 0 ; i < n ; i ++ ) {
31+ let a = w . charAt ( i )
32+ let b = w . charAt ( n - 1 - i )
33+
34+ if ( ! pre . children [ a . charCodeAt ( ) & M ] ) {
35+ pre . children [ a . charCodeAt ( ) & M ] = new Trie ( )
36+ }
37+ if ( ! suf . children [ b . charCodeAt ( ) & M ] ) {
38+ suf . children [ b . charCodeAt ( ) & M ] = new Trie ( )
39+ }
40+
41+ pre = pre . children [ a . charCodeAt ( ) & M ]
42+ suf = suf . children [ b . charCodeAt ( ) & M ]
43+
44+ if ( pre . word && suf . word === pre . word ) {
45+ res += pre . cnt
46+ }
47+ }
48+
49+ if ( ! pre . word ) {
50+ pre . word = w
51+ suf . word = w
52+ }
53+
54+ pre . cnt ++
55+ suf . cnt ++
56+
57+ return res
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments