首页 > 编程语言 > 详细

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

时间:2020-05-07 01:16:01      阅读:215      评论:0      收藏:0      [点我收藏+]
题目:
最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。  如果不存在公共前缀,返回空字符串 ""。

说明:

所有输入只包含小写字母 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题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。

原文:https://www.cnblogs.com/zhuozige/p/12839788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!