- 查找常用字符
- 1.两种解法
- python手动实现
- python3使用collections.Counter
- 2.总结
- python
- 算法
leetcode题目链接
1.两种解法 python手动实现整体思路就是统计出搜索字符串里26个字符的出现的频率,然后取每个字符频率最小值,最后转成输出格式就可以了。
def commonChars(self, words: List[str]) -> List[str]:
hashtable = [0] * 26
hashothertable = [0] * 26
for j,word in enumerate(words):
if j==0:
for i in word:
index = ord(i) - ord('a')
hashtable[index] += 1
else:
hashothertable = [0] * 26
for i in word:
index = ord(i) - ord('a')
hashothertable[index] += 1
for i in range(26):
hashtable[i] = min(hashtable[i],hashothertable[i])
lst = []
for i in range(26):
while hashtable[i] >= 1:
lst.append(chr(ord('a')+i))
hashtable[i] -= 1
return lst
python3使用collections.Counter
使用collections.Counter可以直接进行字符统计,先对每个word求出频率,然后求交集
def commonChars(self, words: List[str]) -> List[str]: tmp = collections.Counter(words[0]) l = [] for i in range(1,len(words)): # 使用 & 取交集 tmp = tmp & collections.Counter(words[i]) # 剩下的就是每个单词都出现的字符(键),个数(值) for j in tmp: v = tmp[j] while(v): l.append(j) v -= 1 return l2.总结 python
- ascii码转字符:chr(ch)
- collections.Counter:直接用来统计容器的每个元素出现的频率
两种解法
- 计算每个word的字母出现频率,然后取最小值
- 计算每个word的字母出现频率,然后取交集



