LeetCode--14. Longest Common Prefix(最长公共前缀子串)

题目:

给定一个包含多个字符串的List,返回所有字符串的最长公共前缀子串。

解题思路:

两层遍历,比较简单,直接上代码。

代码(Python):

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs)==0:
            return ""
        temp_str = strs[0]
        len_temp = len(temp_str)
        for i in strs:
            len_temp = min(len_temp,len(i))
            if len_temp==0:
                return ""
            for j in range(len_temp):
                if i[j]==temp_str[j]:
                    continue
                else:
                    j = j-1
                    break
                    
            temp_str = temp_str[:j+1]
            len_temp = len(temp_str)
            
        return temp_str


猜你喜欢

转载自blog.csdn.net/xiaoxiaoley/article/details/79204756