码迷,mamicode.com
首页 > 编程语言 > 详细

14. Longest Common Prefix [easy] (Python)

时间:2016-06-21 07:26:30      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

题目链接

https://leetcode.com/problems/longest-common-prefix/

题目原文

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

题目翻译

写个函数,找出一个字符串数组中所有字符串的最长公共前缀。
题目描述不清晰。。。补充几个例子,比如:

  1. {“a”,”a”,”b”} 返回 “” ,因为三个字符串没有公共前缀;
  2. {“a”, “a”} 返回 “a” 因为它是两个字符串的公共前缀;
  3. {“abca”, “abc”} 返回 “abc”;
  4. {“ac”, “ac”, “a”, “a”} 返回 “a”。

思路方法

思路一

很直观的思路,从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。

代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ‘‘
        res = ‘‘
        for i in xrange(len(strs[0])):
            for j in xrange(1, len(strs)):
                if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
                    return res
            res += strs[0][i]
        return res

思路二

先将给的字符串数组排序,然后只需要比较第一个和最后一个的公共前缀即可。虽然看起来比前面简单了很多,但实际上排序的代价并不低。

代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ‘‘
        strs.sort()
        res = ‘‘
        for i in xrange(len(strs[0])):
            if i >= len(strs[-1]) or strs[-1][i] != strs[0][i]:
                return res
            res += strs[0][i]
        return res

思路三

用Python的zip()函数,可以实现比较精简的代码,不过效率不高。

代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ‘‘
        for i, chars in enumerate(zip(*strs)):
            if len(set(chars)) > 1:
                return strs[0][:i]
        return min(strs)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51706442

14. Longest Common Prefix [easy] (Python)

标签:

原文地址:http://blog.csdn.net/coder_orz/article/details/51706442

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!