LeetCode:14. 最长公共前缀581. 最短无序连续子数组(python3)

Posted 南岸青栀*

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:14. 最长公共前缀581. 最短无序连续子数组(python3)相关的知识,希望对你有一定的参考价值。

14. 最长公共前缀

在这里插入图片描述

方法1: 纵向扫描法

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
		#纵向扫描法
        com = "" #用来收集LCP
        #特殊情况,只有数组只有一个元素,LCP为本身
        if len(strs)==1: return strs[0]
        #作为字符的索引
        for i in range(len(min(strs))):
            #数组的索引
            for j in range(len(strs)-1):
                #如果出现不匹配的情况直接返回com
                if strs[j][i] != strs[j+1][i]:
                    return com
                #如果匹配到最后一个位置都相同,则将其添加到com中
                elif strs[j][i] == strs[j+1][i] and j+1 == len(strs)-1:
                    com += strs[j][i]
                #没有匹配到最后一个位置,继续匹配
                else: 
                    continue
        return com

改进:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
		#纵向扫描法
        com = "" #用来收集LCP
        #特殊情况,只有数组只有一个元素,LCP为本身
        if len(strs)==1: return strs[0]
        #作为字符的索引
        for i in range(len(min(strs))):
            #数组的索引
            for j in range(len(strs)-1):
                #如果出现不匹配的情况直接返回com
                if strs[j][i] != strs[j+1][i]:
                    return strs[j][:i]
                #没有匹配到最后一个位置,继续匹配
                else: 
                    continue
        return min(strs)

法2: 横向扫描法

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:

        #横向扫描法
        if strs == None: return ""

        prefix,count = strs[0],len(strs)
        for i in range(1,count):
            prefix = self.lcp(prefix, strs[i])
            if not prefix:
                break
        return prefix

    def lcp(self, str1, str2):
        length, index = min(len(str1), len(str2)), 0
        while index < length and str1[index] == str2[index]:
            index += 1
        return str1[:index]

581. 最短无序连续子数组

在这里插入图片描述

思路:

将数组与排列好的数组进行比较,记录前后位置不一样的索引

class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        a = sorted(nums)
        for i in range(len(nums)):
            if nums[i] != a[i]:
                break
        for j in range(len(nums)-1,-1,-1):
            if nums[j] != a[j]: break
        return j-i+1 if i-j != len(nums)-1 else 0

以上是关于LeetCode:14. 最长公共前缀581. 最短无序连续子数组(python3)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-14.最长公共前缀(图)

LeetCode:最长公共前缀14

Leetcode 14 最长公共前缀

Leetcode--最长公共前缀(14)

python(leetcode)-14最长公共前缀

leetcode14-最长公共前缀