14. Longest Common Prefix

Easy

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

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output:
 "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output:
 ""
Explanation:
 There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200

  • 0 <= strs[i].length <= 200

  • strs[i] consists of only lowercase English letters.

解題

因為題目要求的是字串陣列中每個字串共同最長的前綴,所以這個前綴最長也只會和最短的字串一樣長。

解法就是:找出最短的字,接著遞迴它的字元與陣列中其他字串相同位置的字元,比較是否相同。

Runtime: 0 ms, faster than 100.00%

Memory Usage: 2.3 MB, less than 53.88%

func longestCommonPrefix(strs []string) string {
    shortest := strs[0]
    
    for _, str := range(strs) {
        if len(str) < len(shortest) {
            shortest = str
        }
    }
    
    for index, val := range(shortest) {
        for _, str := range(strs) {
            if rune(str[index])!=val {
                return shortest[:index]
            }
        }
    }
    
    return shortest
    
}

Last updated