Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。

Posted 桌子哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。相关的知识,希望对你有一定的参考价值。

题目:
最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。  如果不存在公共前缀,返回空字符串 ""。

说明:

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

思路:

思路较简单。

程序:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        length = len(strs)
        if length == 1:
            return strs[0]
        result = strs[0]
        for index in range(1, length):
            if strs[index] == 0 or not result:
                return ""
            length_min = min(len(result), len(strs[index]))
            auxiliary = ""
            for index2 in range(length_min):
                if result[index2] == strs[index][index2]:
                    auxiliary = auxiliary + result[index2]
                else:
                    break
            result = auxiliary
        return result

以上是关于Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。的主要内容,如果未能解决你的问题,请参考以下文章