leetcode14.最长公共前缀

func longestCommonPrefix(strs []string) string {
    //两两比较
    res:=strs[0]
    for i:=0;i<len(strs);i++{
        res=compare(res,strs[i])
        if len(res)==0{
            return ""
        }
    }
    return res
}
func compare(a,b string)string{
    ans:=make([]byte,0)
    if len(a)==0 || len(b)==0{
        return ""
    }
    min:=len(a)
    if min>len(b){
        min=len(b)
    }
    for i:=0;i<min;i++{
        if a[i]!=b[i]{
            return string(ans)
        }else {
            ans=append(ans,a[i])
        }
    }
    return string(ans)
}

  

上一篇:[学习笔记]Min-Max容斥


下一篇:CF950A Left-handers, Right-handers and Ambidexters 题解