LeetCode热题(五)

回文链表

请判断一个链表是否为回文链表。
在这里插入图片描述
链接:https://leetcode-cn.com/problems/palindrome-linked-list/

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

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        a=[]
        while head:
            a.append(head.val)
            head=head.next
        if a==a[::-1]:
            return True
        return False
#也可以转换为数字或者字符串判断

有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
在这里插入图片描述

链接:https://leetcode-cn.com/problems/valid-parentheses

class Solution:
    def isValid(self, s: str) -> bool:
        a=[]
        dic={')':'(',']':'[','}':'{'}
        for i in s:
            if i in ['(','[','{']:
                a.append(i)
            else:
                if len(a)!=0 and dic[i]==a[-1]:
                    a.pop()
                else:
                    return False
        if len(a)==0:
            return True
        else:
            return False

子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。
在这里插入图片描述
链接:https://leetcode-cn.com/problems/subsets/

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        a=[[]]
        for i in range(len(nums)-1,-1,-1):
            for res in a[:]:
                a.append(res+[nums[i]])
        return a

全排列

给定一个 没有重复 数字的序列,返回其所有可能的全排列。
在这里插入图片描述

链接:https://leetcode-cn.com/problems/permutations/

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        def backtrack(nums, tmp):
            if not nums:
                res.append(tmp)
                return 
            for i in range(len(nums)):
                backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]])
        backtrack(nums, [])
        return res

括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
在这里插入图片描述

链接:https://leetcode-cn.com/problems/generate-parentheses/

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n == 0:
            return [""]
        elif n == 1:
            return ["()"]
        elif n == 2:
            return ["()()", "(())"]
        result = []
        for i in range(n):
            j = n - 1 - i
            temp1 = self.generateParenthesis(i)
            temp2 = self.generateParenthesis(j)
            result.extend(["(%s)%s" % (p, q) for p in temp1 for q in temp2])
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值