最长公共前缀

 

 

最长公共前缀 - LeetCode (中国) https://leetcode-cn.com/problems/longest-common-prefix/description/

 

class Solution:
    def longestCommonPrefix(self, strs):
        """

        :type strs: List[str]
        :rtype: str
        """

        def _longestCommonPrefixIn2(s1, s2):
            """

            :param s1: str
            :param s2: str
            :return: str
            """
            if len(s1) < len(s2):
                short_, long_ = s1, s2
            else:
                short_, long_ = s2, s1
            len_, r = len(short_), ''
            for i in range(len_):
                chk_head = short_[0:i + 1]
                if long_.find(chk_head) == 0:
                    r = chk_head
                else:
                    break
            return r

        if len(strs) == 0 or '' in strs:
            return ''
        elif len(strs) == 1:
            return strs[0]
        elif len(strs) > 1:
            r = _longestCommonPrefixIn2(strs[0], strs[1])
            if r == '':
                return ''
            elif len(strs) > 2:
                for i in strs[2:]:
                    r = _longestCommonPrefixIn2(r, i)
                    if r == '':
                        return ''
            return r

 

posted @ 2018-05-24 21:19  papering  阅读(233)  评论(0编辑  收藏  举报