swift5实现字符串数组中的最长公共前缀- leetcode

208 阅读1分钟
func longestCommonPrefix(_ strs: [String]) -> String {
        // 横向扫描
        if strs.count == 0 || strs[0] == "" {
            return ""
        }
        var prefix = strs[0]
        for i in 1..<strs.count {
            prefix = longestCommonPrefix(prefix, strs[i])
            if prefix.count == 0 {
                break
            }
        }
        return prefix
    }
    func longestCommonPrefix(_ firstStr: String, _ secondStr: String) -> String {
        let length = min(firstStr.count, secondStr.count)
        var index = 0
        var preStr = ""
        while (index < length
               && firstStr[firstStr.index(firstStr.startIndex, offsetBy: index)] == secondStr[secondStr.index(secondStr.startIndex, offsetBy: index)]) {
            preStr.append(firstStr[firstStr.index(firstStr.startIndex, offsetBy: index)] )
            index += 1;
        }
        return preStr
    }