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

运行结果

相关推荐
xlp666hub2 小时前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
东坡肘子4 小时前
Macbook Neo:苹果重回校园的起点 -- 肘子的 Swift 周报 #126
人工智能·swiftui·swift
xlp666hub1 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub1 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
TT_Close5 天前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
张江5 天前
Swift Concurrency学习
swift
东坡肘子7 天前
OpenClaw 不错,但我好像没有那么需要 -- 肘子的 Swift 周报 #125
人工智能·swiftui·swift
琢磨先生David12 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝12 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode