10.24-10.28 leetcode基于python刷题

10.24-10.28 leetcode基于python刷题

说明

从58以后如果显示超时就会采用python自带的计算运行时间,不采用leetcode提交后的显示时间

20. Valid Parentheses(Easy)

'''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

给出一个只包含'(', ')', '{', '}', '['和']'字符的字符串s,判断输入的字符串是否有效。
一个输入的字符串在以下情况下是有效的。
打开的括号必须由相同类型的括号封闭。
开括号必须以正确的顺序关闭。
每个闭合的括号都有一个相同类型的对应的开放括号。
'''

思路

使用栈的数据结构,先进后出,如果是键,就加入栈,如果不是键(即是值),取栈顶的元素,利用字典看与其是否匹配,不匹配就break

代码实现

class Solution1(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """

        dic = {"(":")","{":"}","[":"]"}

        stack = []
        for i in s:
            if i in dic:
                stack.append(i)
            elif len(stack) == 0 or i != dic[stack.pop()] :
                return False
        return len(stack) == 0

s1 = Solution1()
s1 = s1.isValid('()[]{}')
print(s1)

在这里插入图片描述

运行速度

在这里插入图片描述

3. Longest Substring Without Repeating Characters(Medium)

'''
Given a string s, find the length of the longest substring without repeating characters.

给定一个字符串s,找出不重复字符的最长子串的长度。
'''

思路

这道题我并没有想出来,盗用了网上的思路
用下标i-start来计算长度,因为一开始“ ”是为1,所以开始start是-1,当出现重复的元素时,将start赋值为重复元素的下标。

代码实现

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """

        start = -1
        max = 0
        d = {}

        for i in range(len(s)):
            if s[i] in d and d[s[i]] > start:
                start = d[s[i]]
                d[s[i]] = i
            else:
                d[s[i]] = i
                if i - start > max:
                    max = i -start

        return max

s = Solution()
s = s.lengthOfLongestSubstring("pwwkew")
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

27. Remove Element(Easy)

'''
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.

给定一个整数数组nums和一个整数val,就地删除nums中所有出现的val。元素的相对顺序可以被改变。
由于在某些语言中不可能改变数组的长度,你必须让结果放在数组nums的第一部分。更正式地说,如果除去重复的元素后还有k个元素,那么nums的前k个元素就应该放置最终结果。在前k个元素之外留下什么并不重要。
在将最终结果放在nums的前k个槽中后,返回k。
'''

思路

思路1.遍历所有元素,是就加到新的列表,但此题最后要检查原列表,所以要将原列表的前面对应部分变为新的列表。
思路2.发现查找值就与最后一个元素交换,但首指针不能+1,因为不确定交换来的是不是查找值,所以让尾指针-1。

代码实现

class Solution1(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """

        res = []
        for item in nums:
            if item != val:
                res.append(item)

        nums[:len(nums)] = res

        return len(res)

class Solution2(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """

        i = 0
        last = len(nums) - 1
        while i <= last:
            if nums[i] == val:
                nums[i],nums[last] = nums[last],nums[i]
                last -= 1
            else:
                i += 1

        return last+1
        
s1 = Solution1()
s1 = s1.removeElement([3,2,2,3],3)
print(s1)

s2 = Solution2()
s2 = s2.removeElement([3,2,2,3],3)
print(s2)

运行速度

在这里插入图片描述

16. 3Sum Closest(Medium)

'''
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.

给出一个长度为n的整数数组和一个整数目标,在nums中找出三个整数,使其和最接近目标。
返回这三个整数的总和。
'''

思路

这题是15.3Sum的延伸版,依旧在排序后使用双指针,嫌大,就尾指针减小,嫌小,就首指针增加。

代码实现

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """

        def sum(i,left,right,nums):
            return nums[i]+nums[left]+nums[right]

        lens = len(nums)

        res = sum(0, 1, lens - 1, nums)

        nums.sort()
        for i in range(lens-2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            left = i + 1
            right = lens - 1
            while left < right:
                val = sum(i,left,right,nums)
                if abs(val - target) < abs(res - target):
                    res = val
                if val == target:
                    return target
                elif val > target:
                   right -= 1
                else:
                    left += 1

        return res

s1 = Solution()
s1 = s1.threeSumClosest( nums = [-1,2,1,-4], target = 1)
print(s1)

在这里插入图片描述

运行速度

在这里插入图片描述

58. Length of Last Word(Easy)

'''
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.

给定一个由单词和空格组成的字符串s,返回该字符串中最后一个单词的长度。
一个字是一个最大的子串,只由非空格字符组成。
'''

思路

关键在于每次遇到空格后不能直接将count赋值为0,因为会存在最后一个
为空格,这样输出的就是0了。

代码实现

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        res = 0
        for i in range(len(s)):
            if s[i] == ' ':
                count = 0
            else:
                count += 1
                res = count
        return res

s = Solution()
s = s.lengthOfLastWord("   fly me   to   the moon  ")
print(s)

在这里插入图片描述

运行速度在这里插入图片描述

5. Longest Palindromic Substring(Medium)

'''
Given a string s, return the longest palindromic substring in s.
A string is called a palindrome string if the reverse of that string is the same as the original string.

给定一个字符串s,返回s中最长的回文子串。
如果一个字符串的反面与原始字符串相同,则该字符串被称为回文字符串。
'''

思路

思路1遍历所有的情况,每次利用切片,然后利用reverse()函数将其倒序并比较。.
思路2.回文数无非就两种情况,一种是形如’aba’这种,另一种就是’bb’存在连续的,所以我们对每一个元素都像两边扩展,利用双指针:‘aba’,就从b开始,然后双指针依次向两边移动;‘bb’,则左指针是第一个b,右指针是第二个b,然后双指针依次向两边移动。

代码实现

思路1leetcode显示超时,用了一个很长的例子发现一样,因此也是对的。用时间看两个方法的复杂度。

class Solution1(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """

        s = list(s)
        n = len(s)
        dic = {}
        for i in range(n):
            for j in range(i + 1, n + 1):
                a = s[i:j]
                sres = copy.copy(a)
                sres.reverse()
                if a == sres:
                    dic[''.join(a)] = len(a)

        k2 = [k for k, v in dic.items() if v == max(dic.values())]

        return k2[0]

class Solution2(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ''
        for i in range(len(s)):
            len1 = len(self.long(s, i, i))
            if len1 > len(res):
                res = self.long(s, i, i)

            len2 = len(self.long(s, i, i+1))
            if len2 > len(res):
                res = self.long(s, i, i+1)

        return res

    def long(self,s,l,r):
        while l >=0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l+1:r]

starttime = datetime.datetime.now()
s1 = Solution1()
s1 = s1.longestPalindrome("vmqjjfnxtyciixhceqyvibhdmivndvxyzzamcrtpywczjmvlodtqbpjayfchpisbiycczpgjdzezzprfyfwiujqbcubohvvyakxfmsyqkysbigwcslofikvurcbjxrccasvyflhwkzlrqowyijfxacvirmyuhtobbpadxvngydlyzudvnyrgnipnpztdyqledweguchivlwfctafeavejkqyxvfqsigjwodxoqeabnhfhuwzgqarehgmhgisqetrhuszoklbywqrtauvsinumhnrmfkbxffkijrbeefjmipocoeddjuemvqqjpzktxecolwzgpdseshzztnvljbntrbkealeemgkapikyleontpwmoltfwfnrtnxcwmvshepsahffekaemmeklzrpmjxjpwqhihkgvnqhysptomfeqsikvnyhnujcgokfddwsqjmqgsqwsggwhxyinfspgukkfowoxaxosmmogxephzhhy")
endtime = datetime.datetime.now()
print(s1)
print (endtime - starttime)
starttime = datetime.datetime.now()
s2 = Solution2()
s2 = s2.longestPalindrome("vmqjjfnxtyciixhceqyvibhdmivndvxyzzamcrtpywczjmvlodtqbpjayfchpisbiycczpgjdzezzprfyfwiujqbcubohvvyakxfmsyqkysbigwcslofikvurcbjxrccasvyflhwkzlrqowyijfxacvirmyuhtobbpadxvngydlyzudvnyrgnipnpztdyqledweguchivlwfctafeavejkqyxvfqsigjwodxoqeabnhfhuwzgqarehgmhgisqetrhuszoklbywqrtauvsinumhnrmfkbxffkijrbeefjmipocoeddjuemvqqjpzktxecolwzgpdseshzztnvljbntrbkealeemgkapikyleontpwmoltfwfnrtnxcwmvshepsahffekaemmeklzrpmjxjpwqhihkgvnqhysptomfeqsikvnyhnujcgokfddwsqjmqgsqwsggwhxyinfspgukkfowoxaxosmmogxephzhhy")
endtime = datetime.datetime.now()
print(s2)
print (endtime - starttime)

运行速度

在这里插入图片描述

6. Zigzag Conversion(Medium)

'''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);

字符串 "PAYPALISHIRING "以z字形图案写在给定的行数上,像这样:(你可能想用固定的字体显示这个图案,以提高可读性。)
P A H N
A P L S I I G
Y I R
然后逐行阅读。"pahnaplsiigyir"
编写代码,在给定行数的情况下,取一个字符串并进行这种转换。
'''

思路

这是一道很有意思的题目,当numRows是5,是这样的:
在这里插入图片描述
我们可以把每个0-7的位置看出是一组,每一行看出是同一类型的数字,其实就很像哈希表,每一行所对应的键是一样的,每一个键对应了每一行,难点就在于如何存入。法一是笔者的方法,采用数组存放,但这就要想到如果不是整数组,存在多余的的情况,所以就不详细说明了。
思路2.用取余数的方法,例如用0-7这一组,0-4即是本数字%每组数的个数(即是8),当到5-7时,就是余数大于等于numRows即5的时候,就要和与其对应的值共享位置,这个对应的值就是num - i % num,然后呢这样为了加到表里,可以采用str+的方法,看代码就会知道

代码实现

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return ''.join(s)
        n = len(s)
        blocks = int(math.ceil(n / (2 * numRows - 2)))
        yushu = n % (2 * numRows - 2)
        matrix = [[ 0 for _ in range(2 * numRows - 2)] for _ in range(blocks)]


        for i in range(2 * numRows - 2):
            if blocks == 1 and n < 2 * numRows - 2:
                s = list(s)
                for k in  range(yushu,2 * numRows - 2):
                    s.append(0)
            if yushu == 0:
                for j in range(blocks):
                    matrix[j][i] = s[j*(2 * numRows - 2)+i]
            else:
                for j in range(blocks):
                    if j != blocks-1:
                        matrix[j][i] = s[j * (2 * numRows - 2) + i]
                    else:
                        for k in range(yushu):
                            matrix[j][k] = s[j * (2 * numRows - 2) + k]

        res = []
        for i in range(numRows):
            for j in range(blocks):
                if i == 0 or i == numRows-1:
                    res.append(matrix[j][i])
                else:
                    res.append(matrix[j][i])
                    res.append(matrix[j][2 * numRows - 2 - i])

        res2 = copy.copy(res)
        for item in res:
            if item == 0:
                res2.remove(item)

        return ''.join(res2)

starttime = datetime.datetime.now()
s = Solution()
s = s.convert("yjvsbxetkierlqfbxyetjbyqqgrtrurpfmkhjocwyjpjzunxsrqdurtkxngqjxgokqxvgarejgqkadhuuayortbqgjhpgpgsfdolffrqmhbokklgklxdeywnhfepukibqwoxbfqpnrgzdrgocdtidpxmucbqojrghfelnuaangzszhibmcmptjbqnfgcoykyfojskluzuwstdaxqejhyuloiqumguwecnnuzbpzvntoqvliawsatdobtkpzhlejytfauwzrjugcptmrserlhhoaudcboimpdrpaqqrzmxddtqvluoweymgspitfshwwynwqfnqrnvvilstiirmgduyuftzxawvbjrrphjiwffgszzcisqoxlprqkqnloloaehrltzjahpsgqxoknfhywyogrethphhtrahkcsmjkgpcdgnrnwpjxgpqkjxbshwlhfxjyjskqkmtqbkdycovidnuokvjrtubzukzdfjtpxphzzmzbawlfjfuvcfpwbqxvcyzhhuygjhhltgoteaznhvlkaaidqhzsfacoucwekerfmfzrhagpxrbxtlajsbezbgnwklcupvaeabviddxaxazqlbcddgcgoreacixudzyeavofanfxngqyhubmaftqyzqcinylowrotfvusctfijdsdggfnbxnbqsjfqwupokitgcmiwtthxlnfruvtsiuiafprbjgpuq"
,415)
print(s)
endtime = datetime.datetime.now()
print (endtime - starttime)

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        rows = [''] * numRows
        num = (numRows-1) * 2
        for i, item in enumerate(s):
            if i % num >= numRows:
                rows[(num - i % num)] += item
            else:
                rows[i % num] += item
        return ''.join(rows)

starttime = datetime.datetime.now()
s = Solution()
s = s.convert("yjvsbxetkierlqfbxyetjbyqqgrtrurpfmkhjocwyjpjzunxsrqdurtkxngqjxgokqxvgarejgqkadhuuayortbqgjhpgpgsfdolffrqmhbokklgklxdeywnhfepukibqwoxbfqpnrgzdrgocdtidpxmucbqojrghfelnuaangzszhibmcmptjbqnfgcoykyfojskluzuwstdaxqejhyuloiqumguwecnnuzbpzvntoqvliawsatdobtkpzhlejytfauwzrjugcptmrserlhhoaudcboimpdrpaqqrzmxddtqvluoweymgspitfshwwynwqfnqrnvvilstiirmgduyuftzxawvbjrrphjiwffgszzcisqoxlprqkqnloloaehrltzjahpsgqxoknfhywyogrethphhtrahkcsmjkgpcdgnrnwpjxgpqkjxbshwlhfxjyjskqkmtqbkdycovidnuokvjrtubzukzdfjtpxphzzmzbawlfjfuvcfpwbqxvcyzhhuygjhhltgoteaznhvlkaaidqhzsfacoucwekerfmfzrhagpxrbxtlajsbezbgnwklcupvaeabviddxaxazqlbcddgcgoreacixudzyeavofanfxngqyhubmaftqyzqcinylowrotfvusctfijdsdggfnbxnbqsjfqwupokitgcmiwtthxlnfruvtsiuiafprbjgpuq"
,415)
print(s)
endtime = datetime.datetime.now()
print (endtime - starttime)

运行速度

思路1leetcode显示超时,用了一个很长的例子发现一样,因此也是对的。用时间看两个方法的复杂度。
在这里插入图片描述

18. 4Sum(Medium)

'''
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.

给定一个由n个整数组成的数组nums,返回一个由所有唯一的四元组[nums[a], nums[b], nums[c], nums[d]]组成的数组,以便。
0 <= a, b, c, d < n
a, b, c, 和 d 是不同的。
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按任何顺序返回答案。
'''

思路

相较于之前的3 Sum,这题我们可以去在得到结果后去进行判断重复,而不是在得到结果前进行去重。依旧使用双指针。

代码实现

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """

        if len(nums) < 4:
            return []
        nums.sort()
        ans = []
        for i in range(len(nums) - 3):
            for j in range(i+1,len(nums) - 2):
                temp = nums[i] + nums[j]
                p = j + 1
                q = len(nums) - 1
                while p < q:
                    if nums[p] + nums[q] + temp == target:
                        if (nums[i],nums[j],nums[p],nums[q]) not in ans:
                            ans.append((nums[i],nums[j],nums[p],nums[q]))
                    if nums[p] + nums[q] + temp > target:
                        q -= 1
                    else:
                        p += 1

        return ans

s1 = Solution()
s1 = s1.fourSum(nums = [1,0,-1,0,-2,2], target = 0)
print(s1)

在这里插入图片描述

运行速度

在这里插入图片描述

242.Valid Anagram(Medium)

'''
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
给两个字符串s和t,判断t是否为s的重新排列后组成的单词
例如:s = ’anagram‘  t = 'nagaram' 则return true
     s = 'rat'  t = 'car' 则return false
'''

思路

思路1.利用sort()函数排序后进行排序
思路2.用;两个字典,没有ch就取0,有就+1,最后判断两个字典是否相等

代码实现

class Solution1(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sorted(s) == sorted(t)

class Solution2(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dict1 = {}
        dict2 = {}
        for ch in s:
            dict1[ch] = dict1.get(ch,0) + 1  #如果没有ch 就取0
        for ch in t:
            dict2[ch] = dict2.get(ch,0) + 1
        return dict1 == dict2

s1 = Solution1()
s1 = s1.isAnagram('qwer','reqw')
print(s1)

s2 = Solution2()
s2 = s2.isAnagram('qwer','reqw')
print(s2)

在这里插入图片描述

运行速度

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值