码迷,mamicode.com
首页 > 其他好文 > 详细

14. Longest Common Prefix

时间:2016-06-03 12:34:23      阅读:154      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!