LeetCode T14 T26 T27 T28 T35

滑翔小飛俠發表於2021-01-01

在這裡插入圖片描述

class Solution:
    def longestCommonPrefix(self, strs):
        n = len(strs)
        if n==0:
            return ""
        if n==1:
            return strs[0]
        n_s = len(strs[0])
        count = 0
        flag = True
        ch = ""
        if n_s == 0:
            return ""
        ch = strs[0][0]
        while(flag):
            for i in strs:
                n_in = len(i)
                if n_in==0:
                    return ""
                if n_in -1 >= count:
                    if i[count] != ch:
                        flag = False
                        break
                else:
                    return strs[0][:count]
            if flag:
                count += 1
                if n_s -1 >= count:
                    ch = strs[0][count]
                else:
                    break
        if count != 0:
            return strs[0][:count]
        else:
            return ""

在這裡插入圖片描述

在這裡插入圖片描述

class Solution:
    def removeDuplicates(self, nums):
        n = len(nums)
        if n==0:
            return 0
        if n == 1:
            return 1
        temp = nums[0]
        count = 1
        while(count < len(nums)):
            if nums[count] == temp:
                nums.pop(count)
            else:
                temp = nums[count]
                count += 1
        return len(nums)

在這裡插入圖片描述

在這裡插入圖片描述

class Solution:
    def removeElement(self, nums,val):
        n = len(nums)
        if n==0 or (n == 1 and nums[0] == val):
            return 0
        if n == 1:
            return 1
        count = 0
        while(count < len(nums)):
            if nums[count] == val:
                nums.pop(count)
            else:
                count += 1
        return len(nums)

在這裡插入圖片描述
在這裡插入圖片描述

class Solution:
    def strStr(self, haystack, needle):
        if haystack == needle:
            return 0
        n_h = len(haystack)
        n_n =len(needle)
        if n_h<n_n or (n_h == n_n and haystack != needle):
            return -1
        for i in range(n_h - n_n + 1):
            if haystack[i:i+n_n] == needle:
                return i
        return -1

在這裡插入圖片描述

在這裡插入圖片描述

class Solution:
    def searchInsert(self, nums, target):
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            if nums[0] == target:
                return 0
            if nums[0] > target:
                return 0
            if nums[0] < target:
                return 1
        if nums[0] > target:
            return 0
        for i in range(n-1):
            if nums[i] == target:
                return i
            else:
                if nums[i+1]==target:
                    return i + 1
                else:
                    if nums[i+1]<target:
                        continue
                    else:
                        return i+1
        return n
        

在這裡插入圖片描述

相關文章