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

运行结果

相关推荐
叶小鸡21 分钟前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
菜菜的顾清寒1 小时前
力扣HOT100(42)链表-随机链表的复制
算法·leetcode·链表
菜菜的顾清寒4 小时前
HOT力扣100(43)二叉树-翻转二叉树
数据结构·算法·leetcode
csdn_aspnet6 小时前
javascript 算法 LeetCode 编号 70 - 爬楼梯
开发语言·javascript·算法·leetcode·ecmascript
Navigator_Z6 小时前
LeetCode //C - 1073. Adding Two Negabinary Numbers
c语言·算法·leetcode
csdn_aspnet7 小时前
PHP 算法 LeetCode 编号 70 - 爬楼梯
算法·leetcode·php
x_xbx7 小时前
LeetCode:5. 最长回文子串
算法·leetcode·职场和发展
小欣加油11 小时前
leetcode 3300 替换为数位和后的最小元素
数据结构·c++·算法·leetcode
人月神话-Lee11 小时前
【图像处理】Core Image 与 GPU 渲染管线——让滤镜飞起来
图像处理·人工智能·ios·chatgpt·ai编程·swift·gpu
人道领域11 小时前
【LeetCode刷题日记】108.将有序数组转换为二叉搜索树
java·算法·leetcode