Write a function to find the longest common prefix string amongst an array of strings.
题目分析:找出所有字符串的公共前缀。例如:[“asd”,”asdf”,”asdfg”]→asd
方法一:
思路:①如果输入的字符串没有内容,返回“”②如果有内容,以第一个字符串作为标准,先统计它的长度并假设它的长度在所有字符串中最小。③循环其他的字符与标准比较(此时下标是从一开始的,0是之前提到的”标准”),设置一个变量j用来统计公共字串长度,用变量p来存放要比较的字符串。
代码:
class Solution:def longestCommonPrefix(self, strs):if len(strs)==0: return " "Str=strs[0]Min=len(Str)for i in range(1,len(strs)):j=0p=strs[i]while j<Min and j<len(p) and p[j]==Str[j]:j+=1Min=Min if Min<j else jreturn Str[:Min] d=Solution()
c=d.longestCommonPrefix(['asd','asdf','asdfg'])
print(c)
本文发布于:2024-01-27 23:01:06,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063676673166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |