LeetCode 算法题 – Longest Common Prefix

本页内容

编写一个方法返回字符串数组的最长公共前缀。

原题

Write a function to find the longest common prefix string amongst an array of strings.

分析

依据题意,需要注意以下几点:

  • 区分大小写
  • 空数组的处理

实现

 1func longestCommonPrefix(strs []string) string {
 2    if len(strs) == 0 {
 3        return ""
 4    }
 5
 6    max := len(strs[0])
 7
 8    for i := 1; i < len(strs); i++ {
 9        max = min(max, len(strs[i]))
10        for j := 0; j < max; j++ {
11            if strs[i][j] != strs[i-1][j] {
12                max = j
13                continue
14            }
15        }
16    }
17
18    return strs[0][:max]
19}
20
21func min(a, b int) int {
22    if a > b {
23        return b
24    }
25
26    return a
27}