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

运行结果

相关推荐
andyweike3 小时前
Swift
开发语言·ios·swift
旖旎夜光5 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊5 小时前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt5 小时前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊5 小时前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent6 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
静以修身zzz6 小时前
OpenStack对象存储-Swift、OpenStack编排管理-heat、OpenStack网络管理-neutron
linux·运维·服务器·架构·openstack·swift
Pniubi7 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
瓦瓦gogo1 天前
第一次了解 iOS 开发:从 Swift、SwiftUI 到公共组件
ios·swiftui·swift
j7~1 天前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归