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}