The algorithm is simple and swift longest common prefix

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91453030

Write a function to find the longest common prefix string array.

If there is no common prefix, it returns an empty string "."

Example 1:

Input: [ "flower", "flow ", "flight"]
Output: "fl"
Example 2:

Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.

 

solution:

  func longestCommonPrefix(_ strs: [String]) -> String {
        
        var strs = strs
        
        //1.遍历字符串数组中的每一个字符串
        //2.找出最短的字符串
        if(strs.count == 1){
            return strs[0]
        }
        
        for i in 0..<strs.count {
            for j in 0..<strs.count-i-1{
                if(strs[j].count>strs[j+1].count){
                    let temp = strs[j]
                    strs[j] = strs[j+1]
                    strs[j+1] = temp
                }
            }
        }
        //3.从最短的字符串中的第一个字符开始向所有的字符串第一个字符匹配。。。。不匹配则return “”
        var prxStr:String = ""
        //取最短的字符串 判断循环比较次数
        for indexlenth in 0..<strs[0].count {
            
            let str = strs[0]
            let index3 = str.index(str.startIndex, offsetBy: 0)
            let index4 = str.index(str.startIndex, offsetBy: indexlenth+1 > strs[0].count ? strs[0].count : indexlenth+1)
            let sub4 = str[index3..<index4]
            
            //与后面的字符串每一个字符比较
            for indexrow in 1..<strs.count {
                
                let str2 = strs[indexrow]
                let index5 = str2.index(str2.startIndex, offsetBy: 0)
                let index6 = str2.index(str2.startIndex, offsetBy: indexlenth+1 > strs[0].count ? strs[0].count : indexlenth+1)
                let sub7 = str2[index5..<index6]
                
                if sub4 == sub7 {
                    print("相同的值 \(sub4):\(sub7)")
                    prxStr = String(sub4)
                    
                }else{
                    
                    if(prxStr.isEmpty){
                        return ""
                    }else{
                        let index8 = prxStr.index(prxStr.startIndex, offsetBy: 0)
                        let index9 = prxStr.index(prxStr.startIndex, offsetBy: prxStr.count-1)
                        let prxStr = prxStr[index8..<index9]
                        
                        return String(prxStr)
                    }
                    
                }
            }
        }
        
        return prxStr
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91453030