[英]Is there any expression in Swift that is similar to Python's for else syntax
我正在解决一个算法问题,我同时使用 Python 和 Swift 来解决它。 在 python 中,我可以使用 for else 语法轻松解决它。 但是在 Swift 中,我正在努力寻找一种类似于 Python 的其他语法的方法。
这是算法问题,它可以帮助您了解我在做什么。
给定一个字符串数组 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
没有这样的一对词。
这是我的两套代码。
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
swift 代码效果不佳。
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
循环中的for char in item.characters
,因为您可以只使用Set.isDisjointWith(_:)
方法。
if cur_word.isDisjointWith(item.characters) {
maximum = ...
}
(在 Swift 3 中,此方法重命名为Set.isDisjoint(with:)
)
我想分享我的答案。 感谢 Kennytm 的帮助。
class Solution
{
func maxProduct(words: [String]) -> Int
{
var input = words
var 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])
length -= 1
for item in input
{
if cur_word.isDisjointWith(item.characters)
{
maximum = max(maximum, cur_length*(item.characters.count))
}
}
}
return maximum
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.