diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index f7d323aa..c0ca578e 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -268,6 +268,47 @@ func min(a,b int)int{ return a } ``` + +Swift: +```swift +func commonChars(_ words: [String]) -> [String] { + var res = [String]() + if words.count < 1 { + return res + } + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + let lettersMaxCount = 26 + // 用于统计所有字符串每个字母出现的 最小 频率 + var hash = Array(repeating: 0, count: lettersMaxCount) + // 统计第一个字符串每个字母出现的次数 + for unicodeScalar in words.first!.unicodeScalars { + hash[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 统计除第一个字符串每个字母出现的次数 + for idx in 1 ..< words.count { + var hashOtherStr = Array(repeating: 0, count: lettersMaxCount) + for unicodeScalar in words[idx].unicodeScalars { + hashOtherStr[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 更新hash,保证hash里统计的字母为出现的最小频率 + for k in 0 ..< lettersMaxCount { + hash[k] = min(hash[k], hashOtherStr[k]) + } + } + // 将hash统计的字符次数,转成输出形式 + for i in 0 ..< lettersMaxCount { + while hash[i] != 0 { // 注意这里是while,多个重复的字符 + let currentUnicodeScalarValue: UInt32 = UInt32(i) + aUnicodeScalarValue + let currentUnicodeScalar: UnicodeScalar = UnicodeScalar(currentUnicodeScalarValue)! + let outputStr = String(currentUnicodeScalar) // UnicodeScalar -> String + res.append(outputStr) + hash[i] -= 1 + } + } + return res +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)