leetcode with python:14. Longest Common Prefix

题目:

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

给定一个字串阵列,求出他们的 longest common prefix string ,即从前面开始,最长的共同字串
ex:strs = ["flower","flow","flight"] ==> longest common prefix string:"fl"

我的想法是以第一个字串为基础从头开始逐字比较,当确定每个词条的相同位置都是该值时,记录到欲回传的字串
一有不同便回传当下纪录的common prefix string

class Solution:    def longestCommonPrefix(self, strs: List[str]) -> str:        ans=""        for i in range(len(strs[0])):            for j in strs:                if i >len(j)-1:                    return ans                if strs[0][i]!=j[i]:                    return ans            ans=ans+strs[0][i]        return ans

注意:对比时可能会对到超出其他字串的长度,避免out of range,我们需要再加个判断式,一旦超出就回传
最后执行时间37ms(faster than 86.47%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章