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

运行结果

相关推荐
清铎17 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
踩坑记录17 小时前
leetcode hot100 42 接雨水 hard 双指针
leetcode
AlenTech19 小时前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
练习时长一年20 小时前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
栈与堆20 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
努力学算法的蒟蒻21 小时前
day58(1.9)——leetcode面试经典150
算法·leetcode·面试
im_AMBER21 小时前
Leetcode 101 对链表进行插入排序
数据结构·笔记·学习·算法·leetcode·排序算法
踩坑记录1 天前
leetcode hot100 560.和为 K 的子数组 medium 前缀和 + 哈希表
leetcode
独自破碎E1 天前
【队列】按之字形顺序打印二叉树
leetcode
AlenTech1 天前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表