[Swift]LeetCode318. 最大单词长度乘积 | Maximum Product of Word Lengths
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10260623.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a string array words
, find the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
["abcw","baz","foo","bar","xtfn","abcdef"]
16
Explanation:
"abcw", "xtfn"
Example 2:
["a","ab","abc","d","cd","bcd","abcd"]
4
Explanation:
"ab", "cd"
Example 3:
["a","aa","aaa","aaaa"]
0
Explanation:
给定一个字符串数组 words
,找到 length(word[i]) * length(word[j])
的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
示例 1:
["abcw","baz","foo","bar","xtfn","abcdef"]
16
解释: 这两个单词为
"abcw", "xtfn"
示例 2:
["a","ab","abc","d","cd","bcd","abcd"]
4
解释:
"ab", "cd"
示例 3:
["a","aa","aaa","aaaa"]
0
解释: 不存在这样的两个单词。
332 ms
1 class Solution { 2 func maxProduct(_ words: [String]) -> Int { 3 if words.isEmpty { 4 return 0 5 } 6 7 let products = words.map{ProductHelper($0)} 8 9 var res = 0 10 11 for i in 0..<products.count { 12 for j in i+1..<products.count { 13 let p1 = products[i] 14 let p2 = products[j] 15 if p1.characters & p2.characters == 0 { 16 res = max(p1.count * p2.count, res) 17 } 18 } 19 } 20 21 return res 22 } 23 } 24 25 class ProductHelper { 26 let count : Int 27 let characters : Int 28 init(_ s : String) { 29 count = s.count 30 let arr = s.unicodeScalars 31 var r = 0 32 for c in arr { 33 r |= 1 << Int(c.value - 97) 34 } 35 characters = r 36 } 37 }
804ms
1 class Solution { 2 func maxProduct(_ words: [String]) -> Int { 3 let aValue = "a".unicodeScalars.first!.value 4 if words.count <= 1 { return 0 } 5 var array = [Int]() 6 for word in words { 7 var a = 0 8 for c in word.unicodeScalars { 9 a = a | (1 << (c.value - aValue)) 10 } 11 array.append(a) 12 } 13 14 var result = 0 15 for i in 0 ..< array.count - 1 { 16 for j in 1 ..< array.count { 17 if array[i] & array[j] > 0 { 18 continue 19 } 20 result = max(result, words[i].count * words[j].count) 21 } 22 } 23 return result 24 } 25 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了