leetcode 748. 最短完整词

题解

记录牌照licensePlate中每个字母出现的次数,遍历单词表words找出符合要求的最短单词

示例代码(go)

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
func shortestCompletingWord(licensePlate string, words []string) string {
licensePlateMap := make(map[rune]int)
res := ""
for _, v := range licensePlate {
if v >= 'a' && v <= 'z' {
licensePlateMap[v] += 1
}
if v >= 'A' && v <= 'Z' {
licensePlateMap[v -'A' + 'a'] += 1
}
}
for _, word := range words {
if res == "" || len(word) < len(res) {
wordMap := make(map[rune]int)
for _, v := range word {
wordMap[v] += 1
}
flag := true
for k, v := range licensePlateMap {
if v > wordMap[k] {
flag = false
break
}
}
if flag {
res = word
}
}
}
return res
}