微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我试图找到在字符串数组中获取最长字符串的最有效方法.例如 :
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

结果将是 – “权力的游戏是好的”

我尝试过使用maxElement函数,因为它给出了字母思想中的最大字符串(maxElement()).

有什么建议?谢谢!

不要为了良好的排序而对O(n log(n))进行排序,而是使用max(by :),它是Array上的O(n),为它提供一个比较字符串长度的闭包:

斯威夫特4:

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

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

if let max = array.max(by: {$1.count > $0.count}) {
    print(max)
}

斯威夫特3:

在String上使用.characters.count来获取字符串长度:

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

if let max = array.max(by: {$1.characters.count > $0.characters.count}) {
    print(max)
}

斯威夫特2:

在Array上使用maxElement,为它提供一个比较字符串长度的闭包:

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

if let max = array.maxElement({$1.characters.count > $0.characters.count}) {
    print(max)
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐