File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } word
3+ * @param {number } k
4+ * @return {number }
5+ */
6+ const countCompleteSubstrings = function ( word , k ) {
7+ const arr = [ ] , { abs } = Math
8+ const n = word . length
9+ const code = ch => ch . charCodeAt ( 0 )
10+ let i = 0
11+ if ( n === 1 ) arr . push ( word )
12+ for ( let j = 1 ; j < n ; j ++ ) {
13+ const pre = j - 1
14+ if ( abs ( word [ j ] . charCodeAt ( 0 ) - word [ pre ] . charCodeAt ( 0 ) ) > 2 ) {
15+ arr . push ( word . slice ( i , j ) )
16+ i = j
17+ }
18+ if ( j === n - 1 ) {
19+ arr . push ( word . slice ( i ) )
20+ }
21+ }
22+ // console.log(arr)
23+ let res = 0
24+ for ( const str of arr ) {
25+ if ( str === '' ) continue
26+ res += helper ( str )
27+ }
28+
29+ return res
30+
31+
32+ function helper ( str ) {
33+ let res = 0
34+ const n = str . length , a = code ( 'a' )
35+
36+ for ( let i = 1 ; i <= 26 ; i ++ ) {
37+ const len = i * k
38+ const arr = Array ( 26 ) . fill ( 0 )
39+ let pre = 0
40+ for ( let j = 0 ; j < len && j < n ; j ++ ) {
41+ const idx = code ( str [ j ] ) - a
42+ arr [ idx ] ++
43+ }
44+ if ( valid ( arr , i ) ) res ++
45+
46+ for ( let j = len ; j < n ; j ++ ) {
47+ const idx = code ( str [ j ] ) - a
48+ arr [ idx ] ++
49+ const preIdx = code ( str [ pre ] ) - a
50+ arr [ preIdx ] --
51+ if ( valid ( arr , i ) ) res ++
52+ pre ++
53+ }
54+ }
55+
56+ return res
57+ }
58+
59+ function valid ( arr , num ) {
60+ let cnt = 0
61+ for ( const e of arr ) {
62+ if ( e === 0 ) continue
63+ if ( e !== k ) return false
64+ else cnt ++
65+ }
66+
67+ if ( cnt !== num ) return false
68+ return true
69+ }
70+ } ;
71+
72+ // another
73+
74+
175/**
276 * @param {string } word
377 * @param {number } k
You can’t perform that action at this time.
0 commit comments