14. Longest Common Prefix

原创 2018年04月17日 09:44:08

14Longest Common Prefix

题目描述

找出字符串列表中各个字符串的最长公共前缀字符

分析

使用reduce()函数,依次对列表中的字符串调用lcp()内方法,对字符串迭代使用lcp方法来判断。

reduce(function,iterable):依次取出iterable的元素,作为function的参数,并且上一次调用function的返回值,也作为iterable的一个元素

lcp(s1,s2):    循环遍历较短字符串的每个字符,当遇到不同字符时停止,并返回该不同字符之前的所有字符作为返回.

完整代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        def lcp(s1,s2): #内方法
            if len(s1)>len(s2):   #令s1保存较短的字符串
                s1,s2=s2,s1     #两个字符串互换位置
            for i in range(len(s1)):    #遍历较短字符串
                if s1[i]!=s2[i]:    #若第i个字符不一致
                    return s1[:i]   #返回i之前的字符
            return s1   #若s1是s2的前缀,直接返回s1
        return reduce(lcp,strs) if strs else ''     

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
  • hcbbt
  • hcbbt
  • 2015-03-03 15:34:34
  • 3682

LeetCode 14 Longest Common Prefix (C,C++,Java,Python)

Problem: Write a function to find the longest common prefix string amongst an array of strings. ...
  • runningtortoises
  • runningtortoises
  • 2015-05-08 18:40:35
  • 4437

14. Longest Common Prefix [easy] (Python)

题目链接https://leetcode.com/problems/longest-common-prefix/题目原文 Write a function to find the longest ...
  • coder_orz
  • coder_orz
  • 2016-06-18 17:06:51
  • 4643

[LeetCode][14]Longest Common Prefix解析 两种算法和底层源码的深入对比-Java实现

Q: Write a function to find the longest common prefix string amongst an array of strings. A: 这题...
  • u014629433
  • u014629433
  • 2016-06-15 13:12:37
  • 2333

LeetCode 14 Longest Common Prefix(最长公共前缀)(String)

翻译写一个函数(或方法)来寻找一个字符串数组中的最长公共前缀。原文Write a function to find the longest common prefix string amongst a...
  • NoMasp
  • NoMasp
  • 2015-10-16 22:05:46
  • 8357

LeetCode 14 — Longest Common Prefix(C++ Java Python)

题目:http://oj.leetcode.com/problems/longest-common-prefix/ Write a function to find the longest commo...
  • dragon_dream
  • dragon_dream
  • 2014-04-03 18:42:35
  • 2853

[leetcode:python]14.Longest Common Prefix

题目:最长公共前缀 Write a function to find the longest common prefix string amongst an array of strings. 题...
  • NXHYD
  • NXHYD
  • 2017-05-10 19:07:20
  • 1104

14. Longest Common Prefix (计算一组字符串最长公共前缀)

Write a function to find the longest common prefix string amongst an array of strings. public class...
  • xiangwanpeng
  • xiangwanpeng
  • 2016-10-27 17:18:01
  • 200

Longest Common Prefix -- LeetCode

原题链接: http://oj.leetcode.com/problems/longest-common-prefix/  这道题属于字符串处理的题目,思路比较简单,就是brute force的想法,...
  • linhuanmars
  • linhuanmars
  • 2014-03-18 10:01:31
  • 9551

[LeetCode]Longest Common Prefix

题目要求如下: Write a function to find the longest common prefix string amongst an array of strings. 找出所...
  • zhouworld16
  • zhouworld16
  • 2013-11-22 12:37:41
  • 21655
收藏助手
不良信息举报
您举报文章:14. Longest Common Prefix
举报原因:
原因补充:

(最多只允许输入30个字)