3527.找到最常见的问题
implementation, https://leetcode.cn/problems/find-the-most-common-response/
给你一个二维字符串数组 responses,其中每个 responses[i] 是一个字符串数组,表示第 i 天调查的回答结果。
请返回在对每个 responses[i] 中的回答 去重 后,所有天数中 最常见 的回答。如果有多个回答出现频率相同,则返回 字典序最小 的那个回答。
一个字符串 a 在字典序上 小于 另一个字符串 b 的条件是:在第一个不相同的位置上,a 中的字母比 b 中对应的字母在字母表中靠前。
如果前 min(a.length, b.length) 个字符都相同,则较短的字符串字典序更小。
示例 1:
输入: responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]
输出: "good"
解释:
- 每个列表去重后,得到
responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]。 "good"出现了 3 次,"ok"出现了 2 次,"bad"也出现了 2 次。- 返回
"good",因为它出现的频率最高。
示例 2:
输入: responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]
输出: "bad"
解释:
- 每个列表去重后,
responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]。 "bad"、"good"和"ok"都出现了 2 次。- 返回
"bad",因为它在这些最高频率的词中字典序最小。
提示:
1 <= responses.length <= 10001 <= responses[i].length <= 10001 <= responses[i][j].length <= 10responses[i][j]仅由小写英文字母组成
python
from typing import List
from collections import Counter
class Solution:
def findCommonResponse(self, responses: List[List[str]]) -> str:
new_responses = []
for response in responses:
new_responses.append(list(set(response)))
to_list = []
for i in new_responses:
to_list.extend(i)
count = Counter(to_list)
max_count = max(count.values())
most_common = [k for k, v in count.items() if v == max_count]
most_common.sort()
return most_common[0]
if __name__ == "__main__":
sol = Solution()
print(sol.findCommonResponse([["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]))