來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-common-prefix
題目
編寫一個函數來查找字符串數組中的最長公共前綴奸晴。
如果不存在公共前綴悠栓,返回空字符串 ""副渴。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴蔑舞。
示例3:
輸入: ["aflower","bflow","cflight"]
輸出: ""
說明:
所有輸入只包含小寫字母 a-z 谭企。
找出字符串的共有字符堵第,且是前綴矾芙。即從第一個字符開始判斷數組里面的字符串是否相等
方法1-for in遍歷字符串,使用currentStr[..<index]來獲取最后結果
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[..<currentStr.index(currentStr.startIndex, offsetBy: i+1)] != lastStr[..<lastStr.index(lastStr.startIndex, offsetBy: i+1)] {
commonStr = String(currentStr[..<currentStr.index(currentStr.startIndex, offsetBy: i)])
break
}else {
commonStr = String(currentStr[..<currentStr.index(currentStr.startIndex, offsetBy: i+1)])
}
}
}
return commonStr
}
方法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..<min(lastStr.count, currentStr.count) {
let char1 = lastStr[lastStr.index(lastStr.startIndex, offsetBy: i)]
let char2 = currentStr[currentStr.index(currentStr.startIndex, offsetBy: i)]
if char1 == char2 {
commonStr += String(char1)
} else {
break
}
}
return commonStr
}
}
最后
Reduce函數是本次學習的一個新知識點~屬于Swift中的高階函數柴梆,另外還有 Filter, Map, flatmap, compactMap