Longest Common Prefix [LeetCode 14]

1- 问题描述

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


2- 思路分析

  将数组内每个字串转换为List,每次批量取出各列表对应元素存入新列表,对新列表使用set去重。若set长度为1,说明元素一样,算入前缀。


3- Python实现

 1 class Solution:
 2     # @param {string[]} strs
 3     # @return {string}
 4     def longestCommonPrefix(self, strs):
 5         if not strs: return ''
 6         l = len(strs)
 7         if l == 1: return strs[0]
 8         # 方法1 求出最短字串长度再遍历
 9         minlen = min(map(lambda x: len(x), strs))
10         res = []
11         for i in range(minlen):
12             tmp = []
13             for j in range(l):
14                 tmp.append(strs[j][i])    # 各字串i位置字符存入列表
15             if len(set(tmp)) != 1: break    # 若set后长度不等于1,说明存在多种字符
16             res.append(tmp[0])
17         return ''.join(res)    # 拼接出前缀
18 
19         '''
20         # 方法2 不求最短字串长度,若某字串无法取字符,抛出异常
21         res = []
22         for i in range(len(strs[0])):
23             tmp = []
24             for j in range(l):
25                 try:
26                     tmp.append(strs[j][i])
27                 except:
28                     break    # 取不出字符,跳出循环
29             if len(tmp) != l: break    # 若是异常结束循环,已经有部分字符存入tmp,判断是否每个字串都取出字符
30             if len(set(tmp)) != 1: break
31             res.append(tmp[0])
32         return ''.join(res)
33         '''     
原文地址:https://www.cnblogs.com/freyr/p/4504150.html