【问题标题】:Longest Common Prefix with PythonPython 的最长公共前缀
【发布时间】:2020-07-05 15:14:56
【问题描述】:

我正在尝试找出一个简单的 leetcode 问题,但我不知道为什么我的答案不起作用。 问题: 编写一个函数来查找字符串数组中最长的公共前缀字符串。 如果没有公共前缀,则返回一个空字符串“”。 我的代码:

shortest=min(strs,key=len)
strs.remove(shortest)
common=shortest
for i in range(1,len(shortest)):
    comparisons=[common in str for str in strs]
    if all(comparisons):
        print(common)
        break
    else:
        common=common[:-i]

当列表中的字符串长度相同时,上述试验不起作用,但适用于其他情况。 非常感谢。

【问题讨论】:

  • 您能提供示例输入和预期输出吗?

标签: python


【解决方案1】:

朋友,尽量让它像'pythonic'。就像你在现实生活中一样。

在现实生活中你看到了什么?您会看到单词,也许会寻找最短的单词并将其与所有其他单词进行比较。好的,让我们这样做,让我们找到最长的单词,然后找到最短的单词。

首先我们创建一个空字符串,其中两个字符串中相同的字符将被存储

prefix = ''
#'key=len' is a necesary parameter, because otherwise, it would look for the chain with the highest value in numerical terms, and it is not always the shortest in terms of length (it is not exactly like that but so that it is understood haha)
max_sentense = max(strings, key=len)
min_sentense = min(strings, key=len)

好的,现在我们将在现实生活中做什么? 从一开始就一个接一个地循环,在python中可以吗?是的。使用 zip()

for i, o in zip(max_sentense, min_sentense):

“i”将通过最长的字符串,“o”将通过最短的字符串。

好的,现在很简单,我们只需要在 'i' 和 'o' 不同时停止遍历它们,即它们不是同一个字符。

for i, o in zip(max_sentense, min_sentense):

        if i == o:
            prefix += i
        else:
            break

完整代码:

prefix = ''


    max_sentense = max(strings, key=len)
    min_sentense = min(strings, key=len)

    for i, o in zip(max_sentense, min_sentense):

        if i == o:
            prefix += i
        else:
            break
print(prefix)

【讨论】:

    【解决方案2】:

    您可以在列表的单次迭代中相当有效地完成此操作。我把它写得有点冗长,以便更容易理解。

    import itertools
    
    def get_longest_common_prefix(strs):
        longest_common_prefix = strs.pop()
        for string in strs:
            pairs = zip(longest_common_prefix, string)
            longest_common_prefix_pairs = itertools.takewhile(lambda pair: pair[0] == pair[1], pairs)
            longest_common_prefix = (x[0] for x in longest_common_prefix_pairs)
        return ''.join(longest_common_prefix)
    

    【讨论】:

      【解决方案3】:

      在您的代码中,如果存在多个相同长度的字符串,您可以使用最短的字符串进行交叉检查,该字符串可能是最短的字符串之一。此外,最短的可能没有最长的公共前缀。


      这不是一个非常干净的代码,但它可以完成工作

      common, max_cnt = "", 0 
      for i, s1 in enumerate(strs[:-2]): 
          for s2 in strs[i+1:]: 
              for j in range(1, min(len(s1), len(s2))+1): 
                  if s1[:j] == s2[:j]: 
                      if j > max_cnt: 
                          max_cnt = j 
                          common = s1[:j] 
      

      【讨论】:

        【解决方案4】:

        此函数接受任意数量的位置参数。 如果没有给出参数,则返回""。 如果只给出一个参数,则返回它。

        from itertools import zip_longest
        
        def common_prefix(*strings) -> str:
            length = len(strings)
            if not length:
                return ""
            if length == 1:
                return strings[0]
            # as pointed in another answer, 'key=len' is necessary because otherwise
            # the strings will be compared according to lexicographical order,
            # instead of their length
            shortest = min(strings, key=len)
            longest = max(strings, key=len)
            # we use zip_longest instead of zip because `shortest` might be a substring
            # of the longest; that is, the longest common prefix might be `shortest`
            # itself
            for i, chars in enumerate(zip_longest(shortest, longest)):
                if chars[0] != chars[1]:
                    return shortest[:i]
            # if it didn't return by now, the first character is already different,
            # so the longest common prefix is empty
            return ""
        
        
        if __name__ == "__main__":
            for args in [
                ("amigo", "amiga", "amizade"),
                tuple(),
                ("teste",),
                ("amigo", "amiga", "amizade", "atm"),
            ]:
                print(*args, sep=", ", end=": ")
                print(common_prefix(*args))
        

        【讨论】:

          【解决方案5】:

          比较所有单词的第一个字符,然后是第二个字符等是最快的。否则你在做不必要的比较。

          def longestCommonPrefix(self, strs):
              prefix = ''
              for char in zip(*strs):
                  if len(set(char)) == 1:
                      prefix += char[0]
                  else:
                      break
              return prefix
          

          【讨论】:

            【解决方案6】:

            简单的python代码

            def longestCommonPrefix(self, arr):
                
                arr.sort(reverse = False)
                print arr
                n= len(arr)
                str1 = arr[0]
                str2 = arr[n-1]
                
                n1 = len(str1)
                n2 = len(str2)
                result = ""
                j = 0
                i = 0
                
                while(i <= n1 - 1 and j <= n2 - 1):
                    if (str1[i] != str2[j]):
                        break
                    result += (str1[i])
            
                    i += 1
                    j += 1
            
                return (result)
            

            【讨论】:

              猜你喜欢
              • 2021-09-11
              • 1970-01-01
              • 2022-11-22
              • 2018-09-30
              • 2013-04-14
              • 2012-02-01
              • 2020-02-10
              • 2021-10-12
              • 2011-12-23
              相关资源
              最近更新 更多