File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string[] } stickers
3+ * @param {string } target
4+ * @return {number }
5+ */
6+ const minStickers = function ( stickers , target ) {
7+ const isEqual = ( arr1 , arr2 ) => {
8+ for ( let i = 0 ; i < arr1 . length ; ++ i ) if ( arr1 [ i ] !== arr2 [ i ] ) return false
9+ return true
10+ }
11+
12+ const minus = ( arr1 , arr2 ) => {
13+ let res = [ ]
14+ for ( let i = 0 ; i < arr1 . length ; ++ i )
15+ res [ i ] = arr1 [ i ] <= 0 ? arr1 [ i ] : arr1 [ i ] - arr2 [ i ]
16+ return res
17+ }
18+
19+ const isAllNonpositive = arr => {
20+ return arr . every ( item => item <= 0 )
21+ }
22+
23+ const getString = arr => {
24+ return arr . reduce ( ( acc , cur , idx ) => {
25+ if ( cur > 0 ) return acc + String . fromCharCode ( idx + 97 ) . repeat ( cur )
26+ else return acc
27+ } , '' )
28+ }
29+
30+ let ss = stickers . map ( word => {
31+ let tmp = new Array ( 26 ) . fill ( 0 )
32+ for ( let i = 0 ; i < word . length ; ++ i ) tmp [ word . charCodeAt ( i ) - 97 ] ++
33+ return tmp
34+ } )
35+ let root = new Array ( 26 ) . fill ( 0 )
36+ for ( let i = 0 ; i < target . length ; ++ i ) root [ target . charCodeAt ( i ) - 97 ] ++
37+ let cache = new Set ( )
38+ let queue = [ root ]
39+ let size = 0 ,
40+ level = 0 ,
41+ front = null
42+ while ( queue . length !== 0 ) {
43+ size = queue . length
44+ while ( size -- ) {
45+ front = queue . shift ( )
46+ for ( let w of ss ) {
47+ let t = minus ( front , w )
48+ let str = getString ( t )
49+ if ( isEqual ( t , front ) || cache . has ( str ) ) continue
50+ if ( isAllNonpositive ( t ) ) return level + 1
51+ else {
52+ queue . push ( t )
53+ cache . add ( str )
54+ }
55+ }
56+ }
57+ level ++
58+ }
59+ return - 1
60+ }
You can’t perform that action at this time.
0 commit comments