首页 > 其他 > 详细

14. Longest Common Prefix

时间:2016-06-03 12:33:27      阅读:216      评论:0      收藏:0      [点我收藏+]

题目:

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

链接:http://leetcode.com/problems/longest-common-prefix/

一刷:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ‘‘
        length = len(strs[0])
        common_prefix = [‘‘]
        chars_at_idx = set()

        for idx in range(length):
            for one_string in strs:
                if len(one_string) <= idx:
                    return ‘‘.join(common_prefix)
                chars_at_idx.add(one_string[idx])
            if len(chars_at_idx) != 1:
                return ‘‘.join(common_prefix)
            common_prefix.append(chars_at_idx.pop())

        return ‘‘.join(common_prefix)

可以减少中间变量和数据结构的使用:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ‘‘
        length = len(strs[0])

        for idx in range(length):
            char = strs[0][idx]
            for one_string in strs:
                if len(one_string) <= idx or one_string[idx] != char:
                    return one_string[:idx]
        return strs[0]

 

14. Longest Common Prefix

原文:http://www.cnblogs.com/panini/p/5555642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!