题目:
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%)
那我们下题见