Leetcode Golang 14. Longest Common Prefix.go

2019-04-12 11:14:31 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412890

思路

先找到最短的字符串

再循环判断

比较暴力

code

代码语言:javascript复制
func longestCommonPrefix(strs []string) string {
	if len(strs) == 0 {
		return ""
	}
	minLen := math.MaxInt32
	minStr := ""
	//先找到最短的字符串
	for _, v := range strs {
		l := len(v)
		if l < minLen {
			minLen = l
			minStr = v
		}
	}
	long := len(minStr)
	for _, v := range strs {
		for i := 0; i < minLen; i   {
			if minStr[i:i 1] != v[i:i 1] {
				long = int(math.Min(float64(long), float64(i)))
			}
		}
	}
	return minStr[:long]
}

0 人点赞