栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

算法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法

文章目录
  • 查找常用字符
    • 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 l
2.总结 python
  1. ascii码转字符:chr(ch)
  2. collections.Counter:直接用来统计容器的每个元素出现的频率
算法

两种解法

  1. 计算每个word的字母出现频率,然后取最小值
  2. 计算每个word的字母出现频率,然后取交集
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468391.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号