LeetCode 热题 HOT 100(P11~P20)

文章详细介绍了LeetCode中的多个热门问题,涉及括号的有效性检查、链表操作、生成括号组合、合并链表等,主要运用了栈、递归和动态规划的解题技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 系列文章: 

LeetCode 热题 HOT 100(P1~P10)-优快云博客

LeetCode 热题 HOT 100(P11~P20)-优快云博客

LeetCode 热题 HOT 100(P21~P30)-优快云博客

LeetCode 热题 HOT 100(P31~P40)-优快云博客

LC020valid_parentheses

. - 力扣(LeetCode)

题目:

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

解法:

遇到右括号的时候需要判断有没有对应匹配的左括号,因为必须是类型相同的才能进行闭合,因此需要一个栈来维护遇到的左括号,看栈顶的左括号是否跟当前的右括号匹配。

 static Map<Character, Character> cache = new HashMap<>();

    static {
        cache.put(')', '(');
        cache.put('}', '{');
        cache.put(']', '[');
    }

    public boolean isValid(String s) {
        LinkedList<Character> stack = new LinkedList<>();
        for (char c : s.toCharArray()) {
            //  遇到右括号就需要一定要有匹配的左括号
            if (cache.containsKey(c)) {
                if (stack.isEmpty()) {
                    return false;
                }
                if (cache.get(c) != stack.pop()) {
                    return false;
                }

            } else {
                //左括号的情况,直接入栈
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }

这里有个技巧,维护一个右括号为key 的map,这样方便判断和匹配。

LC021merge_two 

. - 力扣(LeetCode)

题目:

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

解法:

遇到链表题,直接创建一个pre 节点,接着轮流比较两边的大小,比较繁琐的是需要判断很多临界情况。

 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode pre = new ListNode();
        ListNode cur = pre;
        while (list1 != null || list2 != null) {
            ListNode next;
            if (list1 == null) {
                next = list2;
                list2 = list2.next;
            } else if (list2 == null) {
                next = list1;
                list1 = list1.next;
            } else {
                if (list1.val < list2.val) {
                    next = list1;
                    list1 = list1.next;
                } else {
                    next = list2;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值