标签:
一、题目
Write a function to find the longest common prefix string amongst an array of strings.
找到一组str的最长前缀
二、解析
这题比较水,只需比较第1、2个str,将相同的前缀记录下来,并拿这个去与第3个str做比较。如果前缀可以融入第三个str,则说明第三个str也有相同前缀,就往下找第4个str。如果不能融入,那就把前缀最后一位去掉,再去判断是否可以融入第三个str,如果不行再去最后一位,如此循环。直到前缀被去完,或者前缀可以融入所有的str为之。还是很好理解的。
三、代码
1 class Solution: 2 # @param {string[]} strs 3 # @return {string} 4 def longestCommonPrefix(self, strs): 5 #in thie problem, we need to find the longest common prefix 6 #i set the result string <str>longest to store the common prefix 7 #first I let longest = strs[0], and to compare each strs[i], do "-" operation 8 #eg:strs=[‘she‘, "shanghai", "super"] 9 #round0: longest = "she", len=3 10 #round1: "she" != "shanghai"[:3], so cut the last one in longest 11 # longest = "sh", len=2 12 # "sh" == "shanghai"[:2],ok ,the next 13 #round2: "sh" != "shper"[:2], cut the last one in longest 14 # longest = "s", len=1 15 # "s" == super[:1], ok, return longest = "s" 16 length = len(strs) 17 if length == 0: 18 return "" 19 elif length == 1: 20 return strs[0] 21 else: 22 longest = strs[0] 23 for i in range(1, length): 24 if strs[i] == "": 25 return "" 26 else: 27 while longest != strs[i][:len(longest)]: 28 len_longest = len(longest) 29 longest = longest[:len_longest - 1] 30 if longest == "": 31 return "" 32 return longest
四、总结
这是两周前A的题了吧,最近一直比较忙,发生了一些变故,没怎么刷题了。其实也不是说没时间,而是有时候累的脑子都不会转了。。还是要多多练手,继续保持节奏。
[LeetCode]#14 Longest Common Prefix
标签:
原文地址:http://www.cnblogs.com/breada/p/4761885.html