From 3caaf866f4e2ec8ce846b261dbf5b07b1a828aa4 Mon Sep 17 00:00:00 2001 From: ironartisan Date: Sat, 7 Aug 2021 10:25:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201002.=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index e3014d00..19f9e128 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -169,6 +169,29 @@ class Solution { } } ``` +```python +class Solution: + def commonChars(self, words: List[str]) -> List[str]: + if not words: return [] + result = [] + hash = [0] * 26 # 用来统计所有字符串里字符出现的最小频率 + for i, c in enumerate(words[0]): # 用第一个字符串给hash初始化 + hash[ord(c) - ord('a')] += 1 + # 统计除第一个字符串外字符的出现频率 + for i in range(1, len(words)): + hashOtherStr = [0] * 26 + for j in range(len(words[0])): + hashOtherStr[ord(words[i][j]) - ord('a')] += 1 + # 更新hash,保证hash里统计26个字符在所有字符串里出现的最小次数 + for k in range(26): + hash[k] = min(hash[k], hashOtherStr[k]) + # 将hash统计的字符次数,转成输出形式 + for i in range(26): + while hash[i] != 0: # 注意这里是while,多个重复的字符 + result.extend(chr(i + ord('a'))) + hash[i] -= 1 + return result +``` javaScript ```js var commonChars = function (words) {