swift solution reduce, map


  • 0
    class Solution {
    	func longestCommonPrefix(_ strs: [String]) -> String {
    		if strs.count == 0{return ""}
    		var idx:Int=0
    		var res:String=String()
    		let nList:[Int] = strs.map({x in x.characters.count})
    		let minLen = nList.min()
    		if minLen == 0{ return ""}
    		while let cc:Character = strs.reduce(strs[0][strs[0].index(strs[0].startIndex,offsetBy:idx)],{ c,s in c == s[s.index(s.startIndex,offsetBy:idx)] ? c : nil }){
    			res+=String(cc)
    			if idx == minLen! - 1{
    				break
    			}
    			idx+=1
    		}
    		return res
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.