字符串数组最长公共前缀
2017-06-23 16:39
656 查看
字符串数组最长公共前缀
Longest Common Prefix
给出字符串数组,查找这个数组中所有字符串的最长公共前缀Write a function to find the longest common prefix string amongst an array of strings.
example 1
input: ['asdqowi','asdb', 'asdmnc'] output: 'asd'
思路
i从0开始自增,判断每个字符串 i 位置的字符是否一致,不一致则 i 之前的串为最长公共字符串。利用python zip函数的特点:
a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9, 10] zip(a, b, c) is => (1, 4, 7) (2, 5, 8) (3, 6, 9) set((1, 1, 1)) = {'1'} set((1, 1, 2)) = {'1', '2'}
zip(*strs)返回可迭代的zip对象,只要判断
set(item)长度大于0,则表明此元素非公共字符。
3. 下面给出两种算法的代码。
代码
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ prefix = '' i = 0 while True: try: tmp = strs[0][i] for item in strs: if item[i] != tmp: return prefix except: #out of index range,表明遍历最短字符串完毕 return prefix prefix += tmp i += 1 return prefix def longestCommonPrefix_use_zip(self, strs): """ :type strs: List[str] :rtype: str """ prefix = '' for _, item in enumerate(zip(*strs)): if len(set(item)) > 1: return prefix else: prefix += item[0] return prefix
本题以及其它leetcode题目代码github地址: github地址
相关文章推荐
- Lettcode_14_Longest Common Prefix——查找字符串数组中最长公共前缀字符串
- longest-common-prefix 求字符串数组的最长公共前缀
- leetcode-14-求字符串数组最长公共前缀
- 寻找一个字符串数组的最长公共前缀
- leetcode-14. Longest Common Prefix(寻找字符串数组最长公共前缀)
- LeetCode 找到一个字符串数组的最长公共前缀
- LeetCode 14. Longest Common Prefix--字符串数组元素的最长公共前缀
- 查找字符串数组中最长的公共前缀字符串。
- PHP实现一个函数查找字符串数组中最长的公共前缀字符串
- LeetCode -- 求字符串数组中的最长公共前缀
- 算法#26--查找字符串数组中最长的公共前缀
- LeetCode -- 求字符串数组中的最长公共前缀
- 找出一个字符串数组中最长公共前缀字符串
- 字符串数组的最长公共前缀
- 求字符串数组最长公共前缀
- POJ 3261 后缀数组 可重叠的,但是要重叠K次的 最长公共前缀最长是多少
- 数组字符串那些经典算法:最大子序列和,最长递增子序列,最长公共子串,最长公共子序列,字符串编辑距离,最长不重复子串,最长回文子串
- ] 找工作知识储备(2)---数组字符串那些经典算法:最大子序列和,最长递增子序列,最长公共子串,最长公共子序列,字符串编辑距离,最长不重复子串,最长回文子串
- hdu4691(后缀数组求最长公共前缀)
- hdu 4691 最长公共前缀 后缀数组 +lcp+rmq