【Leetcode解題】916. Word Subsets
題目
解題概念
- 此題簡單來說,就是要依照
words2的所有字串,回傳對照words1的所有 Universal Set 字串- Subset (子集) 定義 : 若
b字串的所有字母都有出現在a字串中(包含重複)</font,則稱b為a的一個 Subset (子集) - Universal Set (全集) 定義 : 若
words2中的所有b字串都是words1中任一a字串的 Subset,則稱a為 Universal Set
- Subset (子集) 定義 : 若
- 目標函式 :
wordSubsets(words1, words2)- Input :
words1: List[str]、words2: List[str] - Output :
List[str]
- Input :
- 而實際執行上,有兩種以下解法
Method 1 : 直觀寫法
- 解題概念 :
- 用雙重
for迴圈比較word1與word2中的字串 - 用函數比較兩個字串,其中用26格的陣列去存兩個字串的字母分布(a → 0、z → 25)
- 用雙重
- 實際程式碼 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37def wordSubsets(self, words1, words2):
res = [] # 存結果
# 針對所有 words1 與 words2 的字串
for word in words1 :
flag = 0 # 看 word 是否為 Universal Set
for target in words2 :
if not self.match(word, target) : # 比較 word 與 target
# 若有配對失敗,則直接回傳失敗
flag = 1
break
if flag == 0 :
res.append(word)
return res
# 比較 word 與 target
def match(self, word, target) :
# 建立陣列存字母的分布
w_map = [0] * 26
t_map = [0] * 26
# 存兩個字串的分布狀況
for w in word :
w_map[ord(w)-ord('a')] +=1
for t in target :
t_map[ord(t)-ord('a')] +=1
# 若 target 有不同於 word 的字母,則直接回傳 False
for i in range(26):
if t_map[i] > w_map[i] :
return False
return True - 問題 :
:::danger
Runtime Error
:::
Method 2 : 單迴圈寫法
- 解題概念 :
- 先將
words2所有字串的字母分布用for迴圈,存入freq陣列中- 可以直接合併所有字串的分布,因為可以把所有字串視為整個字串
- 用單一
for迴圈比較word1與freq,其中用26格的陣列去存兩個字串的字母分布(a → 0、z → 25)
- 先將
- 實際程式碼 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31def wordSubsets(self, words1, words2):
freq = [0] * 26 # 儲存 words2 所有字串的字母分布
# 針對 words2 做處理
for x in words2 :
temp = [0] * 26
for y in x :
temp[ord(y) - ord('a')] += 1
freq[ord(y) - ord('a')] = max(freq[ord(y) - ord('a')], temp[ord(y) - ord('a')])
res = []
# 接著用 words1 中的字串與 freq 做比較
for x in words1:
temp = [0] * 26
# 先找出 words1 所有字串的字母分布
for y in x :
temp[ord(y) - ord('a')] += 1
flag = 0
for i in range(26) :
# 若 freq 有不同於 temp 的字母,則直接回傳 False
if freq[i] > temp[i] :
flag = 0
break
if flag == 1:
res.append(x)
return res
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


