Swift – 在[String]数组中找到最长字符串的最佳实践
发布时间:2020-12-14 05:23:38 所属栏目:百科 来源:网络整理
导读:我试图找到在字符串数组中获取最长字符串的最有效方法.例如 : let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"] 结果将是 – “权力的游戏是好的” 我尝试过使用maxElement函数,因为它给出了字母思想中的最大字符串(maxElement()
我试图找到在字符串数组中获取最长字符串的最有效方法.例如 :
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)),因此对于大型数组,这将比排序快得多. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |