fast and simple go solution 3ms


  • 0
    func longestCommonPrefix(strs []string) string {
        if len(strs) == 0 {
            return ""
        }
        if len(strs) == 1 {
            return strs[0]
        }
        standard := strs[0]
        match := len(standard)
        for i := 1; i < len(strs); i++ {
            //select the shortest string from strs slice
            if match > len(strs[i]) {
                match = len(strs[i])
                standard = strs[i]
            }
        }
        for i := 0; i < len(strs); i++ {
            for {
                if string(standard[:match]) == string(strs[i][:match]) {
                    break
                } else {
                    match -= 1
                }
                if match == 0 {
                    return ""
                }
            }
        }
        return standard[:match]
    }
    

Log in to reply
 

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