![[LeetCode]题解(python):014-Longest Common Prefix [LeetCode]题解(python):014-Longest Common Prefix](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
题目来源:
https://leetcode.com/problems/longest-common-prefix/
题意分析:
这道题目是要写一个函数,找出字符串组strs的最长公共前缀子字符串。
题目思路:
这都题目的难度是简单。从字符串头部开始计算,初始化公共前缀子字符串是strs[0],公共子字符串每和下一个字符串得到一个新的最新公共前缀子字符串,直到公共前缀子字符串是空或者比较到了最后一个字符串。
代码(python):
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
size = len(strs)
if size == 0:
return ''
if size == 1:
return strs[0]
ans = strs[0]
i = 1
while i < size:
j = 0
minlen = min(len(ans),len(strs[i]))
#print(minlen)
while j < minlen:
if ans[j] != strs[i][j]:
break
j += 1
if j == 0:
return ''
ans = ans[:j]
i += 1
return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4818912.html