题解 | #最长公共前缀#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
func longestCommonPrefix( strs []string ) string {
if len(strs) == 0 {return ""}
var lcp func(int, int) string
lcp = func (start int, end int) string {
if start == end {
return strs[start]
}
mid := start + (end-start)/2
lcpLeft, lcpRight := lcp(start, mid), lcp(mid+1, end)
minLength := min(len(lcpLeft), len(lcpRight))
for i := 0; i < minLength; i++ {
if lcpLeft[i] != lcpRight[i] {
return lcpLeft[:i]
}
}
return lcpLeft[:minLength]
}
return lcp(0, len(strs) - 1)
}
func min(a, b int) int {
if a < b {
return a
}
return b
}