LeetCode 14. Longest Common Pref

2018-11-22  本文已影响13人  费城的二鹏

14. Longest Common Prefix

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """

        if len(strs) == 0:
            return ""
        
        if len(strs) == 1:
            return strs[0]

        index = len(strs[0])
        for i in range(1, len(strs)):
            pos = -1
            for j in range(len(strs[i])):
                if j < len(strs[0]) and strs[0][j] == strs[i][j]:
                    pos = j
                else:
                    break
            index = min(index, pos + 1)
        
        print(strs[0][0:index])
        return strs[0][0:index]

上一篇 下一篇

猜你喜欢

热点阅读