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

【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

 

上一篇:Generate Parentheses - LeetCode


下一篇:Valid Parentheses - LeetCode