[LeetCode]题解(python):014-Longest Common Prefix

题目来源:

https://leetcode.com/problems/longest-common-prefix/


题意分析:

     这道题目是要写一个函数,找出字符串组strs的最长公共前缀子字符串。


题目思路:

     这都题目的难度是简单。从字符串头部开始计算,初始化公共前缀子字符串是strs[0],公共子字符串每和下一个字符串得到一个新的最新公共前缀子字符串,直到公共前缀子字符串是空或者比较到了最后一个字符串。


代码(python):

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         size = len(strs)
 8         if size == 0:
 9             return ''
10         if size == 1:
11             return strs[0]
12         ans = strs[0]
13         i = 1
14         while i < size:
15             j = 0
16             minlen = min(len(ans),len(strs[i]))
17             #print(minlen)
18             while j < minlen:
19                 if ans[j] != strs[i][j]:
20                     break
21                 j += 1
22             if j == 0:
23                 return ''
24             ans = ans[:j]
25             i += 1
26         return ans
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4818912.html

原文地址:https://www.cnblogs.com/chruny/p/4818912.html