Leetcode最长公共前缀运行时错误

时间:2018-12-22 17:04:31

标签: python

这是原始问题: https://leetcode.com/problems/longest-common-prefix/

我能够通过基本测试,但是在线提交时始终会出现运行时错误。另外,当输入为[“”]时无法通过测试。


class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        def pf(x):
            def first(i):
                if len(i)>0:
                    return i[0]
                else: 
                    return ""
            def rest(i):
                if len(i)>1:
                    return i[1:]
                else: 
                    return ""

            first_list = map(first,x)
            compare = len(set(first_list)) ## are all the letter the same

            if compare != 1:
                return []
            else:
                # print "~~~~~~", map(first,x)[0]
                r = map(first,x) + pf(map(rest,x))
                return r


        temp= pf(strs)
        return "".join(list(set(temp)))

1 个答案:

答案 0 :(得分:0)

您不会检查字符是否用完,""[0]会引发索引错误。您还将呼叫"".join(list(set(temp))),因为它会发现逻辑上的问题。

这是一个非常Python化的解决方案。

def longest_prefix(strs):
  prefix = []

  for chars in zip(*strs):
    print chars
    if len(set(chars)) == 1:
      prefix.append(chars[0])
    else:
      break

  return "".join(prefix)

print "prefix=", longest_prefix(["flower","flow","flight"])
print "prefix=", longest_prefix(["flower","flow","float"])
print "prefix=", longest_prefix([""])
prefix= ('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'i')
fl
prefix= ('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'o')
('w', 'w', 'a')
flo
prefix=