[PYTHON] Stack problem: Try to solve "20. Valid Parentheses"

Introduction

I solved the stack problem, so I made a note of it.

Try to solve "20. Valid Parentheses"

Link to problem: https://leetcode.com/problems/valid-parentheses/

answer:


class Solution:
    def isValid(self, s: str) -> bool:
      if len(s)%2 != 0:
        return False

      dic = {'(':')','{':'}','[':']'}
      stack = list()

      for i, c in enumerate(s):
        if s[i] in dic: # verify only left-bracket
          stack.append(s[i]) # add only left-bracket
        else:
          if len(stack) != 0 and dic[stack[-1]] == s[i]:
            stack.pop() # remove a last element
          else:
            return False

      if len(stack) == 0:
        return True

I will explain the flow of this process.

First, create a list called stack, a dictionary with left and right parentheses paired.

Then, look at the input character strings in order from the front, and add them to the stack in the case of left parentheses. (Only the left parenthesis is added to the stack) In the case of right parenthesis, if the last element of the stack is a paired left parenthesis, remove the left parenthesis from the stack. (If not, False is returned and the process ends)

Finally, it returns True if the stack is empty.

Recommended Posts

Stack problem: Try to solve "20. Valid Parentheses"
Try to solve the fizzbuzz problem with Keras
Try to solve the Python class inheritance problem
Try to solve the internship assignment problem with Python
Try to solve the N Queens problem with SA of PyQUBO
Try to solve the function minimization problem using particle swarm optimization
Want to solve a simple classification problem?
How to solve the bin packing problem
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
Try to solve a set problem of high school math with Python
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to calculate a statistical problem in Python
Try to solve the traveling salesman problem with a genetic algorithm (execution result)
Try to solve the man-machine chart with Python
Try to solve the programming challenge book with python3
[Python] Try to read the cool answer to the FizzBuzz problem
Try to solve the problems / problems of "Matrix Programmer" (Chapter 1)
Try to solve Sudoku in various ways (SAT, CSP)
I tried to solve the problem with Python Vol.1
Try to solve Sudoku at explosive speed using numpy
Try to implement yolact
I tried to solve a combination optimization problem with Qiskit
Try to solve the problems / problems of "Matrix Programmer" (Chapter 0 Functions)
The problem becomes easier to solve depending on the formulation method