当前位置:网站首页>String longest common prefix

String longest common prefix

2022-06-25 10:06:00 Morris_

LC The longest common prefix

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

If no common prefix exists , Returns an empty string “”.

Input :strs = [“flower”,“flow”,“flight”]
Output :“fl”

swift Realization

class ViewController: UIViewController {
    

    override func viewDidLoad() {
    
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let strs = ["flower","flow","flight"]
        //let strs = ["dog","racecar","car"]
        //let strs = ["ab", "a"]
        //let strs = ["flower","flower","flower","flower"]
        print(longestCommonPrefix(strs))
    }
    
    func longestCommonPrefix(_ strs: [String]) -> String {
    
        
        if strs.count == 0 {
    
            return ""
        }

        if strs.count == 1 {
    
            return strs[0]
        }
        
        //  Traverse by first string 

        let array = Array(strs[0])
        
        for i in 0..<array.count {
    
            
            let c = array[i]
            
            var index = 1
            while index < strs.count {
    
                
                let temp = Array(strs[index])
                
                if temp.count > i {
    
                
                    if c != temp[i] {
    
                        
                        if i > 0 {
    
                            return String(strs[0].prefix(i))
                        }
                        else {
    
                            return ""
                        }
                    }
                }
                else {
    
                    return String(strs[0].prefix(i))
                }
                
                index += 1
            }
        }
        
        return strs[0]
    }
}

Ideas :

 Please add a picture description

原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250915051727.html