原题链接:
https://leetcode.cn/problems/number-of-matching-subsequences/
法1:分桶排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package main
func numMatchingSubseq(s string, words []string) int { d := make([][]string,26) for _, w := range words { u := w[0] - 'a' d[u] = append(d[u], w) }
ans := 0 for i := 0; i < len(s); i++ { u := s[i] - 'a' for _, w := range d[u] { if w[0] - 'a' == u { if len(w) == 1 { ans++ } else { d[w[1]-'a'] = append(d[w[1]-'a'], w[1:]) } } d[u] = d[u][1:] } }
return ans }
|
法2: 二分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package main
import ( "sort" )
func numMatchingSubseq(s string, words []string) int { d := [26][]int{} for i, ch := range s { u := ch - 'a' d[u] = append(d[u], i) }
check := func(w string) bool { i := -1 for k := 0; k < len(w); k++ { c := w[k] - 'a' j := sort.SearchInts(d[c], i+1) if j == len(d[c]) { return false } i = d[c][j] }
return true } ans := 0 for _, w := range words { if check(w) { ans++ } } return ans }
|