美文网首页
14.最长公共前缀

14.最长公共前缀

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-05 19:38 被阅读0次

    https://leetcode-cn.com/problems/longest-common-prefix/

    func longestCommonPrefix(_ strs: [String]) -> String {
        if strs.count <= 0 {return ""}
        var preStr = strs[0]
        for (index, str) in strs.enumerated() {
            if index == 0 {continue}
            while !str.hasPrefix(preStr) {
                let startIndex = preStr.index(preStr.startIndex, offsetBy: 0)
                let endIndex = preStr.index(preStr.startIndex, offsetBy: (preStr.count - 1))
                //每次删除末尾一个字符
                let tmpStr = preStr[startIndex..<endIndex]
                preStr = String(tmpStr)
                if preStr.count == 0 {return ""}
            }
        }
        return preStr
    }
    
    

    相关文章

      网友评论

          本文标题:14.最长公共前缀

          本文链接:https://www.haomeiwen.com/subject/ybgcrhtx.html