Problem
Problem page: https://leetcode.com/problems/valid-parentheses/
Topics: Stack, String
Difficulty: Easy
Similar problems: (M) Generate Parentheses, (H) Longest Valid Parentheses
Given a string containing just the characters
'(',')','{','}','['and']', determine if the input string is valid.The brackets must close in the correct order,
"()"and"()[]{}"are all valid but"(]"and"([)]"are not.
Analysis
I bet we all did this problem in college, though that version might have been a little simpler since we only had to match parentheses. Here we have three kinds of brackets to deal with, but it's still just as easy.
I use a stack to keep track of the opening brackets. Each time I see a closing bracket, I pop an opening bracket off the stack and check whether it matches the closing bracket. Once I've gone through all the brackets, I check whether the stack is empty.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-valid-parentheses/
