14. 最长公共前缀

14. 最长公共前缀

Show me the code

swift 复制代码
class Solution {
    func longestCommonPrefix(_ strs: [String]) -> String {
        var ret = ""
        var stop = false
        let firstString = strs.first!
        guard !firstString.isEmpty else {
        	// 首个字符串是""
            return ""
        }
        var prefix = ""
        for maxLength in 1...firstString.count {
            prefix = String(firstString.prefix(maxLength))
            for str in strs {
                if !str.hasPrefix(prefix) {
                    ret = String(firstString.prefix(maxLength - 1))
                    stop = true
                    break
                }
            }
            if stop {
                break
            }
        }
        // 首个str整个都是前缀
        if !stop {
            ret = firstString
        }
        return ret
    }
}

运行结果

相关推荐
6Hzlia7 分钟前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
py有趣5 小时前
力扣热门100题之接雨水
算法·leetcode
py有趣8 小时前
力扣热门100题之合并区间
算法·leetcode
派大星~课堂8 小时前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
py有趣8 小时前
力扣热门100题之最小覆盖子串
算法·leetcode
北顾笙9809 小时前
day15-数据结构力扣
数据结构·算法·leetcode
人道领域10 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙98010 小时前
day16-数据结构力扣
数据结构·算法·leetcode
wsoz10 小时前
Leetcode子串-day4
c++·算法·leetcode
会编程的土豆10 小时前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode