Skip to content

Latest commit

 

History

History
46 lines (46 loc) · 1.4 KB

14.md

File metadata and controls

46 lines (46 loc) · 1.4 KB

14. Longest Common Prefix

题目链接

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ''
        prefix = strs[0]
        for data in strs:
            length = len(prefix)
            # 如果前缀的长度比字符串长,则交换
            if len(data) < length:
                prefix , data = data, prefix
                length = len(prefix)
            while data[:length] != prefix:
                prefix = prefix[:-1]
                length -= 1
            # 如果长度为0,意味着没有公共前缀,所以返回0
            if length == 0:
                return ''
        return prefix

一个可读性更好的方法(性能较差)

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ''
        prefix = strs[0]
        for data in strs:
            # 如果前缀的长度比字符串长,则交换
            if len(data) < len(prefix):
                prefix , data = data, prefix
            # 找到该字符串的最小前缀
            while data.find(prefix) != 0:
                prefix = prefix[:-1]
        return prefix