[LeetCode] 1002. Find Common Characters 查找共同字符
题目
题意
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
思路
每个字符串都仅由26个小写字母组成。那么,创建若干个长度为26的数组,统计每个字符串中每个字母出现的次数。然后再顺序统计全部字符串中同一个字符出现次数最少的个数,即为该字符的共同出现次数。
代码
func commonChars(A []string) []string {
result := []string{}
count := make([][26]byte, len(A))
for i, str := range A {
for _, c := range str {
count[i][c-'a']++
}
}
for i:=0; i < 26; i++ {
var max byte = count[0][i]
if max == 0 {
continue
}
for j:=1; j < len(A); j++ {
if count[j][i] == 0 {
max = 0
break
}
if count[j][i] < max {
max = count[j][i]
}
}
for max > 0 {
result = append(result, string(i+'a'))
max--
}
}
return result
}