【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists...

本文深入解析了LeetCode上的三个经典算法题目:移除链表倒数第N个节点、验证括号序列的有效性以及合并两个有序链表。通过详细的代码实现和思路讲解,帮助读者理解并掌握这些算法题目的解决方法。

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

【Q19】

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

 

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

class Solution:
    def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode':
        
        cur = head
        length = 0
        while cur!=None:
            cur = cur.next
            length += 1
            
        if length==0:
            return head
        else:
            idx = 0
            if length-n==0:
                return head.next
            else:
                cur = head
                while idx<length-n-1:
                    cur = cur.next
                    idx += 1
                cur.next = cur.next.next
                return head

 

【Q20】

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

解法:用堆栈。遍历字符串数组,把左括号全部压栈,遇到右括号时,判断与栈顶的左括号是否为一对,若是,则令栈顶的左括号出栈,判断遍历完毕的栈是否为空。若是,则返回True,否则返回False。
详解(直接看最后的solution):https://leetcode.com/problems/valid-parentheses/solution/
class Solution:
    def isValid(self, s: 'str') -> 'bool':
        
        charmap = {')':'(',']':'[','}':'{'}
        if s==None:
            return True
        
        if len(s)%2!=0:
            return False
        
        stack = []
        for i in range(len(s)):
            if i==0:
                stack.append(s[i])
            elif s[i] in charmap:
                c = stack.pop()
                if c!=charmap.get(s[i]):
                    return False
            else:
                stack.append(s[i])
        return not stack

 

【Q21】

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4


注意保存链表头!
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
        
        head = l = ListNode(None)
        
        while l1 and l2:
            if l1.val<l2.val:
                l.next = l1
                l1 = l1.next
            else:
                l.next = l2
                l2 = l2.next
            l = l.next
        if not l1:
            l.next = l2
        else:
            l.next = l1
        return head.next

 

转载于:https://www.cnblogs.com/YunyiGuang/p/10353454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值