Swift - 在[String]数组中找到最长字符串的最佳实践

Roi*_*lia 11 sorting string max maxlength swift

我试图找到在字符串数组中获取最长字符串的最有效方法.例如 :

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
Run Code Online (Sandbox Code Playgroud)

结果将是 - "Game Of Thrones is just good"

我尝试过使用maxElementfunc,因为它以字母的形式给出了最大字符串(maxElement()).

有什么建议?谢谢!

vac*_*ama 30

而不是排序哪个是O(n log(n))以获得良好的排序,max(by:)而是在Array上使用O(n),为它提供一个比较字符串长度的闭包:

斯威夫特4:

对于Swift 4,您可以使用count属性获取字符串长度String:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.max(by: {$1.count > $0.count}) {
    print(max)
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3:

使用.characters.counton String来获取字符串长度:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.max(by: {$1.characters.count > $0.characters.count}) {
    print(max)
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特2:

使用maxElementArray为它提供一个闭包来比较字符串长度:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.maxElement({$1.characters.count > $0.characters.count}) {
    print(max)
}
Run Code Online (Sandbox Code Playgroud)

注意: maxElementO(n).一个好的排序是O(n log(n)),因此对于大型数组,这将比排序快得多.


Ham*_*ish 5

你可以reduce用来做这件事.它将迭代您的数组,跟踪当前最长的字符串,然后在完成后返回它.

例如:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let longestString = array.reduce(Optional<String>.None, combine:{$0?.characters.count > $1.characters.count ? $0:$1}) {
    print(longestString) // "Game Of Thrones is just good"
}
Run Code Online (Sandbox Code Playgroud)

(注意,Optional.None现在Optional.none在Swift 3中)

这使用nil起始值来说明数组可能为空的事实,正如@JHZ所指出的那样(nil在这种情况下它会返回).如果您知道您的数组至少有一个元素,则可以将其简化为:

let longestString = array.reduce("") {$0.characters.count > $1.characters.count ? $0:$1}
Run Code Online (Sandbox Code Playgroud)

因为它只迭代每个元素一次,所以它比使用更快sort().我做了一个快速的基准测试并且sort()出现了大约20倍的速度(尽管在过早优化方面没有任何意义,我觉得值得一提).


编辑:我建议你使用@ vacawama的解决方案,因为它甚至更清洁reduce!