LeetCode算法题-14.|LeetCode算法题-14. 最长公共前缀(Swift)
来源:力扣(LeetCode)题目
链接:https://leetcode-cn.com/problems/longest-common-prefix
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
示例3:
输入: ["aflower","bflow","cflight"]
输出: ""
说明:方法1-for in遍历字符串,使用currentStr[..
所有输入只包含小写字母 a-z 。
找出字符串的共有字符,且是前缀。即从第一个字符开始判断数组里面的字符串是否相等
func longestCommonPrefix(_ strs: [String]) -> String {if strs.count <= 0 {
return ""
}
var commonStr:String = strs[0]
for str in strs {let lastStr = commonStr //上一个
let currentStr = str //当前字符串
if (currentStr.count <= 0) {
return ""
}
if lastStr == currentStr {
continue
}
//遍历每一位得值
for i in 0..<(currentStr.count < lastStr.count ? currentStr.count : lastStr.count) {if currentStr[..
方法2-使用reduce函数遍历字符串,获取字符,然后拼接成字符串得结果
func longestCommonPrefix(_ strs: [String]) -> String {if strs.count <= 0 {
return ""
}
return strs.reduce(strs[0]) { (lastStr,currentStr) in
var commonStr = ""
if lastStr == currentStr {
return currentStr
}
//遍历每一位得值
for i in 0..
最后
【LeetCode算法题-14.|LeetCode算法题-14. 最长公共前缀(Swift)】Reduce函数是本次学习的一个新知识点~属于Swift中的高阶函数,另外还有 Filter, Map, flatmap, compactMap
推荐阅读
- parallels|parallels desktop 解决网络初始化失败问题
- jhipster|jhipster 升级无效问题
- “精神病患者”的角度问题
- 画解算法(1.|画解算法:1. 两数之和)
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- Guava|Guava RateLimiter与限流算法
- 解决SpringBoot引用别的模块无法注入的问题
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 迷茫是人生常态