@@ -46,40 +46,46 @@ const suggestedProducts = function(products, searchWord) {
46
46
* @param {string } searchWord
47
47
* @return {string[][] }
48
48
*/
49
- const suggestedProducts = function ( products , searchWord ) {
49
+ const suggestedProducts = function ( products , searchWord ) {
50
+ products . sort ( )
50
51
const root = new Node ( )
51
- for ( const str of products ) {
52
+ for ( const str of products ) {
52
53
addProduct ( str )
53
54
}
54
55
55
56
const res = [ ]
56
57
57
58
let cur = root
58
- for ( const ch of searchWord ) {
59
+ for ( const ch of searchWord ) {
59
60
const tmp = [ ]
60
- if ( cur == null ) {
61
- res . push ( tmp )
62
- continue
61
+ if ( cur == null ) {
62
+ res . push ( tmp )
63
+ continue
63
64
}
64
65
const map = cur . children . get ( ch )
65
- if ( map != null ) {
66
- const arr = [ ...map . words ]
67
- arr . sort ( )
68
- tmp . push ( ...arr . slice ( 0 , 3 ) )
66
+ if ( map != null ) {
67
+ addThree ( map . words . values ( ) , tmp )
69
68
}
70
69
71
70
res . push ( tmp )
72
71
cur = map
73
72
}
74
73
75
-
76
74
return res
77
-
75
+
76
+ function addThree ( it , arr ) {
77
+
78
+ for ( let i = 0 ; i < 3 ; i ++ ) {
79
+ const res = it . next ( )
80
+ if ( res . value ) arr . push ( res . value )
81
+ }
82
+ }
83
+
78
84
function addProduct ( str ) {
79
85
let cur = root
80
- for ( const ch of str ) {
86
+ for ( const ch of str ) {
81
87
let next = cur . children . get ( ch )
82
- if ( next == null ) {
88
+ if ( next == null ) {
83
89
next = new Node ( )
84
90
cur . children . set ( ch , next )
85
91
}
@@ -88,12 +94,13 @@ const suggestedProducts = function(products, searchWord) {
88
94
}
89
95
cur . isWord = true
90
96
}
91
- } ;
97
+ }
92
98
93
99
class Node {
94
100
constructor ( ) {
95
- this . children = new Map ( )
96
- this . words = new Set ( )
97
- this . isWord = false
101
+ this . children = new Map ( )
102
+ this . words = new Set ( )
103
+ this . isWord = false
98
104
}
99
105
}
106
+
0 commit comments