Posted on 2023-02-09 19:46
Uriel 閱讀(53)
評論(0) 編輯 收藏 引用 所屬分類:
字符串處理 、
閑來無事重切Leet Code 、
Hash
給出一堆候選公司名(str),每次從中任意選兩個,如果交換首字母之后的兩個單詞在原先的候選名單里都沒有出現,那么拼合這兩個單詞之后的公司名為最終候選公司名,問一共可以組成幾個候選公司名
Python的set()用法,參考了Discussion->https://leetcode.com/problems/naming-a-company/solutions/3162477/clean-codes-full-explanation-set-of-array-c-java-python3/
1 #2306
2 #Runtime: 513 ms (Beats 66.67%)
3 #Memory: 33.1 MB (Beats 50%)
4
5 class Solution(object):
6 def distinctNames(self, ideas):
7 """
8 :type ideas: List[str]
9 :rtype: int
10 """
11 suf = [set() for _ in range(26)]
12 for c in ideas:
13 suf[ord(c[0]) - ord('a')].add(c[1:])
14 ans = 0
15 for i in range(25):
16 for j in range(i + 1, 26):
17 cnt = len(suf[i] & suf[j])
18 ans += 2 * (len(suf[i]) - cnt) * (len(suf[j]) - cnt)
19 return ans