🤹🏼

# 916. Word Subsets | Swift | July LeetCoding Challenge 2022

2022/07/30に公開

## 題目

2022/7/30 ，July LeetCoding Challenge 2022 的題目

## 思路

### Hash Map

``````facebook
``````

``````["f": 1, "a": 1, "c": 1, "e": 1, "b": 1, "o": 2, "k": 1]
``````

## 程式碼

``````class Solution {
func wordSubsets(_ words1: [String], _ words2: [String]) -> [String] {
var result = [String]()

// MARK: - 統整出 word2 的 hash map

var words2Map = [Character: Int]()
for word in words2 {
// 1. 計算出每個字元出現的次數
var map = [Character: Int]()
for character in word {
map[character, default: 0] += 1
}

// 2. 如果有出現最大值，紀錄到 words2Map
for (character, value) in map {
words2Map[character] = max(words2Map[character] ?? 0, value)
}
}

// MARK: - 走訪 words1 的每一個元素。來和 words2Map 比較

word1: for word in words1 {
// 1. 計算出每個字元出現的次數
var map = [Character: Int]()
for character in word {
map[character, default: 0] += 1
}

// 2. 和 words2Map 比較
for (character, value) in words2Map {
if (map[character] ?? 0) < value {
continue word1
}
}
result.append(word)
}

return result
}
}
``````

## 分析

• `n` - words1 中所有的字元數
• `m` - words2 中所有的字元數

O(n + m)

O(n + m)

ログインするとコメントできます