Swift, use NSString.substring(to:)


  • 0
    X
    class Solution {
        func longestCommonPrefix(_ strs: [String]) -> String {
            let sz = strs.count
            var result : String = ""
            if(sz <= 1 || strs[0]=="") { return sz==0 ? result : strs[0]; }
            
            // B : just compair from the first str: 
            for i in 0...strs[0].characters.count-1 {
                let idxA = strs[0].index(strs[0].startIndex, offsetBy: i)
                for s in 1...sz-1 {
                    if i >= strs[s].characters.count {
                        return strs[s]
                    }
                    let idxB = strs[s].index(strs[s].startIndex, offsetBy: i)
                    if strs[0][idxA] != strs[s][idxB] {
                        if i == 0 { return "" }
                        return NSString(string: strs[0]).substring(to: i)
                    }
                }
            }
            return strs[0]
        }
    }
    

Log in to reply
 

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