LeetCode Link: https://leetcode.com/problems/longest-common-prefix/
Description:
Write a function to find the longest common prefix string amongst an array of strings.
写一个函数找到一个String类型的数组中的最长公共前缀。
If there is no common prefix, return an empty string "".
如果没有公共前缀,返回空字符串。
All given inputs are in lowercase letters a-z.
所有输入只包含小写字母 a-z 。
Example:
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Tints:
1.找到长度最短的字符串,并将其看作最长公共前缀commonPrefix。
2.在数组中遍历,检查是否每个元素都包括commonPrefix,如果没有,commonPrefix去掉最后一个字母,继续循环
Solution:
import Foundation
func longestCommonPrefix(_ strs: [String]) -> String {
var shortest: String? // 长度最短的字符串
var length = Int.max // 最短字符串的长度
for str in strs {
if str.count < length {
length = str.count
shortest = str
}
}
if var commonPrefix = shortest {
var endIndex = commonPrefix.endIndex
for str in strs {
while !commonPrefix.isEmpty && !str.hasPrefix(commonPrefix) {
endIndex = commonPrefix.index(before: endIndex) // endIndex 减 1
commonPrefix = String(commonPrefix.prefix(upTo: endIndex)) // 公共前缀减去最后一个字母
}
}
return commonPrefix
} else {
return ""
}
}