简繁EN

LeetCodeNo. 094

【LeetCode with Python】 14. Longest Common Prefix

目錄

題目

原題頁面:https://leetcode.com/problems/longest-common-prefix/
題目型別:String
難度評價:Easy

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


分析

很簡單的題目,找一堆字串的最長公共字首。先找str1和str2的最長公共字首例如str1_2,再找str1_2和str3的最長公共字首str1_2_3……


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-longest-common-prefix/