LeetCode practice day 6 (20, effective parentheses 21, merge two ordered linked lists)

persistence is victory

Table of contents

1. Valid parentheses

1. Topic:

Example 1:

Example 3:

hint:

2. Ideas

idea:

Supplementary knowledge:

3. The usage of the stack

4. Code (python):

2. Merge two ordered linked lists 

1. Topic:

2. Ideas

idea:

Supplementary knowledge:

3. Code (python)


1. Valid parentheses

1. Topic:

Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

An opening parenthesis must be closed with a closing parenthesis of the same type.
Opening parentheses must be closed in the correct order.
Each closing parenthesis has a corresponding opening parenthesis of the same type.

Example 1:

Input: s = "()"
Output: true
 

Example 3:

Input: s = "(]"
Output: false

hint:

  • 1 <= s.length <= 104
  • s'()[]{}' consists  only of parentheses 

2. Ideas

idea:

Need to pair, first you can judge whether the string is an even number, if it is not an even number, return false;

To process closing brackets, you need to see if there are matching opening brackets in front, so you can use the stack. Every time the left parenthesis is pushed onto the stack, the right parenthesis depends on whether the top of the stack is a matching left parenthesis. If it is not, there is a problem; such as
[ ), it cannot be matched. If it is matched, the top of the stack will be popped off. Finally, it is judged whether all the left parentheses in the stack are out of order.

Supplementary knowledge:

1. The colon (:) represents a whole, and where the colon appears, it represents the position of the whole.

2. enumerate() is a built-in function of python, applicable to python2.x and python3.x;
enumerate appreciates the meaning of enumeration and enumeration in the dictionary;
enumerate parameters are traversable/iterable objects (such as lists, strings);
enumerate is mostly used to get the count in the for loop, and it can be used to obtain the index and value at the same time, that is, enumerate can be used when index and value values ​​are needed;

enumerate() returns an enumerate object 

3. mapping is a mapping function

For details, please refer to this note:

[Python study notes] 4. Mapping (Mapping)_mapping in python_Dramaturge's Blog-CSDN Blog

3. The usage of the stack

The abstract data type of a stack is defined by the following structures and operations. As mentioned above, a stack is structured as an ordered collection of items, where the position at which items are added and removed from the end is called the "top". Stacks are ordered LIFO. The stack operates as follows.
Stack() creates a new, empty stack. It takes no arguments and returns an empty stack.
push(item) adds a new item to the top of the stack. It takes item as parameter and returns nothing.
pop() removes the top item from the stack. It takes no parameters and returns item. The stack is modified.
peek() returns the top item from the stack, but does not remove it. No parameters are required. The stack is not modified.
isEmpty() tests whether the stack is empty. Takes no parameters and returns a boolean.
size() returns the number of items in the stack. Takes no parameters and returns an integer.

 The reference here is the blog of Python implementation stack_木水_-CSDN blog , you can read this note for details

4. Code (python):


class Solution:
    def isValid(self, s: str) -> bool:
        mapping={"}":"{",")":"(","]":"["}
        stack=[]
        if len(s)%2!=0:
            return False#字符串长度不是偶数直接返回false
        for i ,char in enumerate(s):#对于字符串中的每个字符进行判别,遍历
            if char not in mapping:
                stack.append(char)#左半部分压入栈底
            else:
                if not stack or stack[-1]!=mapping[char]:
                    return False#如果是右半部分与栈底元素比较是否匹配,如果不匹配或者栈此时为空返回false
                stack.pop()#将左半部分弹出栈
        return len(stack)==0

2. Merge two ordered linked lists 

1. Topic:

Merges two ascending lists into a new ascending list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists. 

Example 1:


Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

hint:

  • The range of the number of nodes of the two linked lists is [0, 50]
  • -100 <= Node.val <= 100
  • l1 and  l2 both in  non-decreasing  order

2. Ideas

idea:

Just compare and merge directly according to the size relationship.
Newly created newhead
(1) If both L1 and L2 exist, loop; compare the size of L1 and L2 nodes in turn, and store the smaller one in L3; *
           If L1 is smaller, L1 Store in L3 [that is, store val in L3], and the L1 node will be moved backward;
           * If L2 is small, L2 will be stored in L3, and the L2 node will be moved backward;
(2) If one of L1 and L2 does not exist, the subsequent All nodes are assigned to L3;

Supplementary knowledge:

Linked list structure Linked
list (linked list) is a physically non-continuous, non-sequential data structure, composed of several nodes ( node ).

A linked list is a non-sequential and non-sequential storage structure on a physical storage unit, and the logical order of data elements is realized through the link order of pointers in the linked list. The linked list is composed of a series of nodes (each element in the linked list is called a node), and the nodes can be dynamically generated at runtime. Each node consists of two parts: one is a data field that stores data elements, and the other is a pointer field that stores the address of the next node. Compared with the linear list sequential structure, the operation is more complicated. Since it does not have to be stored in order, the linked list can reach the complexity of O(1) when inserting, which is much faster than another linear list sequence table, but it takes O(n) to find a node or access a specific numbered node time, and the corresponding time complexities of linear table and sequential table are O(logn) and O(1) respectively.
 

    #Insert head
        elif index == 0:
            node.next = self.head
            self.head = node
        #Insert tail
        elif index == self.size:
            self.last.next = node
            self.last = node
            #Not needed here Let node.next point to None, and it points to None by default
        #Insert the middle
        else:
            pre_node = self.get(index-1)#Find the front node of the inserted node
            node.next = pre_node.next
            pre_node.next = node
        self.size += 1 #Don't forget to add 1 to the number of nodes in the linked list after inserting a node

    def remova(self, index):
        if index < 0 or index >= self.size:
            raise Exception("Out of the range of linked list nodes!")
        #Temporarily store the deleted node for return
        #Delete head node
        if index = = 0:
            remove_node = self.head
            self.head = self.head.next
        #delete tail node
        elif index == self.size:
            pre_node = self.get(index-1)
            remove_node = pre_node.next
            pre_node.next = None
            self .last = pre_node
        #Delete intermediate nodes
        else:
            pre_node = self.get(index-1)
            next_node = pre_node.next.next
            remove_node = pre_node.next
            pre_node.next = next_node
        self.size -= 1 #Don't forget to delete the node, the number of nodes in the linked list should be reduced by 1
        return remove_node
 

For specific operations, you can see the data structure commonly used in Python---linked list_python linked list_algorithm programmer &mlh's blog-CSDN blog

3. Code (python)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        newhead=ListNode(0)#创建新链表
        p=newhead
        while list1!=None and list2!=None:#在两个链表都不为空的时候,比较list1和list2的大小,依次放入新链表中
            if list1.val<=list2.val:
                p.next=ListNode(list1.val)
                list1=list1.next
            else:
                p.next=ListNode(list2.val)
                list2=list2.next
            p=p.next
        if list1!=None:#有链表空了,将没空的链表其余部分全部放入新链表
            p.next=list1
        else:
            p.next=list2
        return newhead.next#一定是return newhead.next,如果是return newhead返回的新链表会多出一个0,答案不正确。

Guess you like

Origin blog.csdn.net/m0_51786204/article/details/129852569