题目:

【leetcode系列】【py3】【中等】最长公共前缀

原题链接: https://leetcode-cn.com/problems/longest-common-prefix/

 

解题思路:

使用最短字符的长度作为总长度

使用类似二分查找的思想,从中间开始比对字符串

如果左半部分字符串相同,则继续比对右半部分字符串中的左半部分

如果左半部分字符串不同,则比对左半部分字符串中的左半部分

直到查到最长公共子串

 

代码实现:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if 0 == len(strs):
            return ""
        elif 1 == len(strs):
            return strs[0]
        
        low = 1
        high = min([len(a) for a in strs])
        while low <= high:
            mid = int((low + high) / 2)
            
            tmp_flag = True
            for curr_str in strs[1:]:
                if curr_str[:mid] == strs[0][:mid]:
                    continue
                else:
                    high = mid - 1
                    tmp_flag = False
                    break
                    
            if True == tmp_flag:
                low = mid + 1
                
        return strs[0][0:int((low + high) / 2)]

相关文章:

  • 2021-06-01
  • 2021-07-28
  • 2021-12-16
  • 2021-09-20
  • 2021-04-30
  • 2022-03-07
  • 2021-06-15
  • 2022-12-23
猜你喜欢
  • 2021-06-26
  • 2021-06-05
  • 2021-08-31
  • 2022-02-04
  • 2021-06-30
  • 2021-04-02
相关资源
相似解决方案