我正在解决算法问题,并且同时使用Python和Swift来解决它。在python中,我可以使用for else语法轻松解决它。但是在Swift中,我努力寻找一种与python for else语法类似的方法。
这里是算法问题,它可以帮助您了解我在做什么。
给出一个字符串数组单词,求出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”]
Return 4
这两个词可以是“ ab”,“ cd”。
示例3:给定[“ a”,“ aa”,“ aaa”,“ aaaa”]
返回0
没有这样的单词。
这是我的两套代码。
Python代码有效。
class Solution(object):
def maxProduct(self, words):
maximum = 0
while words:
currentWord = set(words[0])
current_length = len(words[0])
words = words[1:]
for ele in words:
for char in currentWord:
if char in ele:
break
else:
maximum = max(maximum,current_length*len(ele))
return maximum
快速代码无法正常工作。
class Solution
{
func maxProduct(words: [String]) -> Int
{
var input = words
let length = input.count
var maximum = 0
while input.count != 0
{
let cur_word = Set(input[0].characters)
let cur_length = input[0].characters.count
input = Array(input[1..<length])
for item in input
{
for char in item.characters
{
if cur_word.contains(char)
{
break
}
}
// how add a control follow here? if cur_word does not share same character with item, then does the below max statement
//else
//{
maximum = max(maximum,cur_length*(item.characters.count))
//}
}
}
return maximum
}
}
您可以引入一个标志来记录是否调用break
。声明
for a in b:
if c(a):
break
else:
d()
与]相同>
found = False for a in b: if c(a): found = True break if not found: d()
但是请注意,您根本不需要
for char in item.characters
循环,因为您可以只使用Set.isDisjointWith(_:)
method。
Set.isDisjointWith(_:)
(在Swift 3中,此方法为
if cur_word.isDisjointWith(item.characters) { maximum = ... }
)
我想分享我的答案。感谢Kennytm的帮助。