LeetCode刷题之20,21,26,27,28收获汇总

20、有效的括号(给定一个只包含'()','[]','{}'的字符串,判断字符串是否有效)

def isValid(self, s):
        def isMatch(c1,c2):
            if c1=='(' and c2==')':
                return True
            elif c1=='[' and c2==']':
                return True
            elif c1=='{' and c2=='}':
                return True
            else:
                return False
        if s=='':
            return True
        s1=[]
        if s[0] in [')',']','}']:
            return False
        for x in s:
            if x in ['(','[','{']:
                s1.append(x)
            elif x in [')',']','}']:
                if len(s1)==0:
                    return False
                if isMatch(s1[-1],x):
                    s1.pop()
                    if len(s1)==0 and x==s[-1]:
                        return True
                    else:
                        continue
                else:
                    return False
        if len(s1)!=0:
            return False
 这个题目在语法上首先是get到了pop函数的使用,括号里要放的是倒数第几个元素的标号,默认为1,并且pop反悔的是删去的元素。然后是逻辑上,依旧要求考虑的很周到,括号匹配的题目之前在数据结构里做过,但是忘得差不多了。然后上网查了别人的思路原来那个原理是栈,那么在Python中与栈对应的应该是append和pop函数,左括号先存到一个list中,遇到右括号将它和左括号的最后一个元素进行匹配,匹配成功则删去那个元素(这里要自己定义一个ismatch函数),然后在提交过程中依旧是暴露了我逻辑上的不完整,首先是'['情况,在这里进行修改如果最终s1(左括号所在列表)长度不为0则不匹配,然后是'([]'情况,在这里进行修改如果后面遇到右括号但是len(s1)为0则不匹配,然后是'[])'情况这里进行修改只有len(s1)为0并且循环到了s的最后一个元素才返回true。

21、合并两个有序链表。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):  
        """ 
        :type l1: ListNode 
        :type l2: ListNode 
        :rtype: ListNode 
        """  
        if l1==None:
            return l2
        if l2==None:
            return l1
        if l1.val<l2.val:
            r1=l1
            l1=l1.next
        else:
            r1=l2
            l2=l2.next
        r2=r1
        while(l1!=None or l2!=None):
            if l1==None:
                r1.next=l2
                return r2
            if l2==None:
                r1.next=l1
                return r2
            if l1.val>l2.val:
                r1.next=l2
                l2=l2.next
                r1=r1.next
                continue
            if l1.val<=l2.val:
                r1.next=l1
                l1=l1.next
                r1=r1.next
                continue
        return r2
 对于链表操作,要注意指针的使用,用两个指针遍历这两个链表,将当前两个指针的较小的一个内容接在返回链表的最后,再将该较小指针后移一位,直到其中一个指针的内容为空,则结束。
26、删除排序数组中的重复项。(要求不能使用额外的空间)
def removeDuplicter(nums):
    i=0
    l=len(nums)
    for j in range(l):
        if nums[j]!=nums[i]:
            i+=1
            nums[i]=nums[j]
    print(nums)
    return i+1

这个题目首先想到的是set结构,然后用list中的sort函数进行排序,但是这样会引进额外空间(虽然运行时间很短),然后经过改正用覆盖的方法来更新元素。

27、移除元素(同样是不能引入额外空间)

def removeElements(nums,val):
    i=0
    l=len(nums)
    while i<l:
        if nums[i]==val:
            del nums[i]
        else:
            i+=1
        l=len(nums)
    return nums
用了删除和覆盖两种方法
def removeElements(nums,val):
    j=0
    for i in range(len(nums)):
        if nums[i]!=val:
            nums[j]=nums[i]
            j+=1
    print(nums)
    return j
28、实现strStr()函数( 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回   -1
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle=='':
            return 0
        for i in range(len(haystack)):
            if haystack[i:i+len(needle)]==needle:
                return i
            i+=1
        return -1
用到了str的切片,逻辑比较简单,但是运行时间较长。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值