Write a function to find the longest common prefix string amongst an array of strings.
class Solution: # @return a string #最长公共前缀 def longestCommonPrefix(self, strs): if strs is None or strs ==[]:return ‘‘ result =‘‘ pre =None for cur in xrange(len(strs[0])): for node in strs: if len(node) <=cur: return result if pre is not None: if pre != node[cur]: return result pre =node[cur] result+=pre pre=None return result
随便选一个strs中的元素的长度来遍历即可,无需选择strs中的最小元素,因为我在循环中加了一句
if len(node) <=cur:
return result
来判断其他元素是否越界。
164 ms
leetcode Longest Common Prefix 最长公共前缀 (python)
原文:http://www.cnblogs.com/zhidan/p/4007294.html