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

运行结果

相关推荐
篮l球场1 天前
数组中的第K个最大元素
数据结构·算法·leetcode
篮l球场1 天前
前 K 个高频元素
数据结构·算法·leetcode
_深海凉_1 天前
LeetCode热题100-两数之和
算法·leetcode·职场和发展
阿Y加油吧1 天前
面试硬核双杀!合并 K 个升序链表 + LRU 缓存|力扣高频手撕原题全解
数据结构·leetcode·链表
老鼠只爱大米1 天前
LeetCode经典算法面试题 #70:爬楼梯(朴素递归、记忆化递归、动态规划等六种实现方案详解)
算法·leetcode·动态规划·递归·斐波那契·矩阵快速幂·爬楼梯
旖-旎1 天前
位运算(两整数之和)(3)
c++·算法·leetcode·位运算
x_xbx2 天前
LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
愣头不青2 天前
96.不同的二叉搜索树
数据结构·算法·leetcode
alphaTao2 天前
LeetCode 每日一题 2026/3/23-2026/3/29
服务器·windows·leetcode
不光头强2 天前
力扣78子集题解
算法·leetcode·深度优先