LeetCode算法题-14. 最长公共前缀(Swift)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix

题目

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

示例3:

输入: ["aflower","bflow","cflight"]
输出: ""

说明:
所有输入只包含小写字母 a-z 。
找出字符串的共有字符,且是前缀。即从第一个字符开始判断数组里面的字符串是否相等

方法1-for in遍历字符串,使用currentStr[..
func longestCommonPrefix(_ strs: [String]) -> String {
        
        if strs.count <= 0 {
            return ""
        }
        var commonStr:String = strs[0]
        for str in strs {
            
            let lastStr = commonStr //上一个
            let currentStr = str //当前字符串
            if (currentStr.count <= 0) {
                return ""
            }
            if lastStr == currentStr {
                continue
            }
            //遍历每一位得值
            for i in 0..<(currentStr.count < lastStr.count ? currentStr.count : lastStr.count) {
                
                if currentStr[..

方法2-使用reduce函数遍历字符串,获取字符,然后拼接成字符串得结果

func longestCommonPrefix(_ strs: [String]) -> String {
        
        if strs.count <= 0 {
            return ""
        }
        return strs.reduce(strs[0]) { (lastStr,currentStr) in
            var commonStr = ""
            if lastStr == currentStr {
                return currentStr
            }
            //遍历每一位得值
            for i in 0..

最后

Reduce函数是本次学习的一个新知识点~属于Swift中的高阶函数,另外还有 Filter, Map, flatmap, compactMap

你可能感兴趣的:(LeetCode算法题-14. 最长公共前缀(Swift))