LeetCode EP.8
20. Valid Parentheses
Published in
Jun 24, 2022
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
思路
這裡照Example給的下去做測試的話會發現自己很多想法上的漏洞,可能一開始就很興奮的直接寫下去了。
初步的想法是把'('
, ')'
, '{'
, '}'
, '['
,']'
變成 HashMap,然後再FilterNot 掉 Key & Value 即可,但提交之後才發現是錯的因為還有其他種可能像是(){}}{
或是([)]
。
後來轉個念想說這些必然是一對的,那先把一對的去掉即可,剩下來去不掉的一定就不符合括號的原則,所以我們先把{}
,[]
,()
去掉後續一定會還有可以湊成這三種括號的,沒有的話就會 return false。
解答
那如果想玩玩看的話也可以參考我的 Github 使用 IntelliJ 就可以 Build 了,裡面也寫了 Test 來驗證。