14. 最长公共前缀

71 阅读1分钟

题目: 编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

解法:

func longestCommonPrefix(strs []string) string {
    if len(strs) == 0 {
        return ""
    }
    ans := strs[0]
    for i := 1; i < len(strs); i ++ {
        j := 0
        for ; j < len(strs[i]); j ++ {
            
            if j < len(ans) && ans[j] == strs[i][j] {
                continue
            }
            break
        }
        ans = ans[:j]
    }
    return ans
}