type dirNode struct { child [26]*dirNode indexList []int }
funcsuggestedProducts(products []string, searchWord string) [][]string { var res [][]string sort.SliceStable(products, func(i, j int)bool { return products[i] < products[j] }) var pro func(i, index int, d *dirNode) pro = func(i, index int, d *dirNode) { if i > 0 { d.indexList = append(d.indexList, index) } if i >= len(products[index]) { return } if d.child[products[index][i]-'a'] == nil { d.child[products[index][i]-'a'] = new(dirNode) } pro(i+1, index, d.child[products[index][i]-'a'])
} dir := dirNode{} for i := 0; i < len(products); i++ { pro(0, i, &dir) } var sea func(i, max int, d *dirNode) sea = func(i, max int, d *dirNode) { var temp []string if i >= max { for j := 0; j < len(d.indexList) && j < 3; j++ { temp = append(temp, products[d.indexList[j]]) } res = append(res, temp) return } if d.child[searchWord[i]-'a'] == nil { res = append(res, temp) return } sea(i+1, max, d.child[searchWord[i]-'a']) }
for i := 0; i < len(searchWord); i++ { sea(0, i+1, &dir) }