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
    }
}

运行结果

相关推荐
一个不知名程序员www1 小时前
leetcode第189题:轮转数组(C语言版)
c语言·leetcode
一叶祇秋2 小时前
Leetcode - 周赛417
算法·leetcode·职场和发展
夜雨翦春韭4 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
一直学习永不止步4 小时前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
戊子仲秋5 小时前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
￴ㅤ￴￴ㅤ9527超级帅6 小时前
LeetCode hot100---二叉树专题(C++语言)
c++·算法·leetcode
liuyang-neu6 小时前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一个不知名程序员www6 小时前
leetcode面试题17.04:消失的数字(C语言版)
leetcode
penguin_bark6 小时前
LCR 068. 搜索插入位置
算法·leetcode·职场和发展
爱上语文9 小时前
Java LeetCode每日一题
java·开发语言·leetcode