简繁EN

LeetCodeNo. 094

[LeetCode with Python] 14. Longest Common Prefix

Contents

Problem

Problem page: https://leetcode.com/problems/longest-common-prefix/
Topics: String
Difficulty: Easy

Write a function to find the longest common prefix string amongst an array of strings.


Analysis

Pretty easy problem: find the longest common prefix of a bunch of strings. First find the longest common prefix of str1 and str2, say str1_2, then find the longest common prefix of str1_2 and str3, str1_2_3, and so on...


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:

def findPrefix(self, str1, str2):
min_len = min(len(str1), len(str2))
for i in range(0, min_len):
if str1[i] != str2[i]:
return str1[0:i]
return str1[0:min_len]

# @return a string
def longestCommonPrefix(self, strs):
if None == strs:
return ""
n = len(strs)
if 0 == n:
return ""
elif 1 == n:
return strs[0]

prefix = strs[0]
for str in strs[1:]:
prefix = self.findPrefix(prefix, str)
if "" == prefix:
break
return prefix

Article link: https://xnerv.wang/en/leetcode-longest-common-prefix/