0014. Longest Common Prefix - chasel2361/leetcode GitHub Wiki

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: ["flower","flow","flight"]
Output: "fl"

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

這個問題我解不出來,所以直接參考別人的寫法。

這邊主要是利用python的max以及min函式,用在string的時候此二函式會回傳出依據字母排序的最大最小結果,比方說

max(["flower","flow","flight"]) -> flower
max(["dog","racecar","car"]) -> racecar
min(["flower","flow","flight"]) -> flight
min(["dog","racecar","car"]) -> car

因此只要將max及min逐字比較即可

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ""
        s1 = max(strs)
        s2 = min(strs)        
        for i, c in enumerate(s2):
            if c != s1[i]:
                return s2[:i]
        return s2

Code Link