算法每日一刷

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

2019-06-10  本文已影响0人  entre_los_dos

来源:力扣(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[..<index]来获取最后结果

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[..<currentStr.index(currentStr.startIndex, offsetBy: i+1)] != lastStr[..<lastStr.index(lastStr.startIndex, offsetBy: i+1)] {
                    commonStr = String(currentStr[..<currentStr.index(currentStr.startIndex, offsetBy: i)])
                    break
                }else {
                commonStr = String(currentStr[..<currentStr.index(currentStr.startIndex, offsetBy: i+1)])
                }
                
            }
        }
        
        return commonStr
    }

方法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..<min(lastStr.count, currentStr.count) {
                
                let char1 = lastStr[lastStr.index(lastStr.startIndex, offsetBy: i)]
                let char2 = currentStr[currentStr.index(currentStr.startIndex, offsetBy: i)]
                
                if char1 == char2 {
                    commonStr += String(char1)
                } else {
                    break
                }
                
            }
            return commonStr
        }
    
    }

最后

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

上一篇下一篇

猜你喜欢

热点阅读