【Leetcode】Python实现最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:
所有输入只包含小写字母 a-z 。

方法一:
只需要比较逐个字母ASCII码值,谁先出现小于的话,则为最小值
比较到最后则为最大值的存在,可以使用print()或者ipython测试

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        # 判断是否为空
        if not strs:
            return ''
        # 在使用max和min的时候已经把字符串比较了一遍
        # 当前列表的字符串中,每个字符串从第一个字母往后比较直至出现ASCII码 最小的字符串
        s1 = min(strs)
        # 当前列表的字符串中,每个字符串从第一个字母往后比较直至出现ASCII码 最大的字符串
        s2 = max(strs)
        # 使用枚举变量s1字符串的每个字母和下标
        for i, c in enumerate(s1):
            # 比较是否相同的字符串,不相同则使用下标截取字符串
            if c != s2[i]:
                return s1[:i]
        return s1


if __name__ == '__main__':
    s = Solution()
    print(s.longestCommonPrefix(["flower", "flow", "flight"]))
    print('123', s.longestCommonPrefix(["dog", "racecar", "car"]))

方法二:直接调用os.path封装好的函数commonprefix,可以查看源代码,其实现和上面的代码完全一样,但是多了调用耗时可能稍微长一点

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        import os
        return os.path.commonprefix(strs)

源码图:
实现源码图

猜你喜欢

转载自blog.csdn.net/chenhua1125/article/details/80542344
今日推荐