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

题目:

【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)]