给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"]
输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"]
输出:["c","o"]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] 由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
参考:
python
# 1002.查找共用字符串
class Solution:
def commonChars(self, words: [str]) -> [str]:
"""
哈希法,
思路:
- 先统计第一个字符串的字符
- 遍历words数组,从第二个字符串开始
- 统计当前字符串
- 比较前哈希与当前哈希对应字符次数,取小值
- 遍历完words数组后,处理返回结果
- 处理多次出现的字符
:param words:
:return:
"""
if not words:
return []
res = []
hash = [0] * 26
for i,ch in enumerate(words[0]):
hash[ord(ch) - ord('a')] += 1
for i in range(1, len(words)):
hashOtherStr = [0] * 26
for j in range(len(words[i])):
hashOtherStr[ord(words[i][j]) - ord('a')] += 1
for k in range(26):
hash[k] = min(hash[k], hashOtherStr[k])
for i in range(26):
while hash[i] != 0:
res.extend(chr(i + ord('a')))
hash[i] -= 1
return res
golang
package main
func commonChars(words []string) []string {
length := len(words)
frequence := make([][]int, 0)
res := make([]string, 0)
// 统计词频
for i := 0; i < length; i++ {
var row [26]int
for j := 0; j < len(words[i]); j++ {
row[words[i][j]-97]++
}
frequence = append(frequence, row[:])
}
// 查找一列的最小值
for j := 0; j < len(frequence[0]); j++ {
pre := frequence[0][j] // 字符出现次数
for i := 0; i < len(frequence); i++ {
pre = min(pre, frequence[i][j])
}
// 按次数将字符添加到返回结果中
tmpStr := string(j + 97)
for i := 0; i < pre; i++ {
res = append(res, tmpStr)
}
}
return res
}
func min(a, b int) int {
if a < b {
return a
}
return b
}