Longest Common Prefix

发布时间 2023-06-13 10:36:01作者: Artwalker

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.

Solution:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:  # 如果列表为空,则返回一个空字符串
            return ""  
        prefix = strs[0]  
        for s in strs[1:]:  
            while not s.startswith(prefix):  
                prefix = prefix[:-1]  # prefix[:-1]表示选取前缀prefix序列中除了最后一个字符以外的所有字符
                if not prefix:  # 如果最终没有找到任何前缀,则返回一个空字符串
                    return ""  
        return prefix