LeetCode EP.8

20. Valid Parentheses

Photo by Balazs Busznyak on Unsplash

Given a string s 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.

Example 1:

Example 2:

Example 3:

Constraints:

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

思路

這裡照Example給的下去做測試的話會發現自己很多想法上的漏洞,可能一開始就很興奮的直接寫下去了。

初步的想法是把'(', ')', '{', '}', '[' ,']' 變成 HashMap,然後再FilterNot 掉 Key & Value 即可,但提交之後才發現是錯的因為還有其他種可能像是(){}}{ 或是([)]

後來轉個念想說這些必然是一對的,那先把一對的去掉即可,剩下來去不掉的一定就不符合括號的原則,所以我們先把{} ,[] ,() 去掉後續一定會還有可以湊成這三種括號的,沒有的話就會 return false。

解答

那如果想玩玩看的話也可以參考我的 Github 使用 IntelliJ 就可以 Build 了,裡面也寫了 Test 來驗證。

--

--

陳建維 Ben
工程師求生指南(Sofware Engineer Survival Guide)

喜愛新鮮知識充滿好奇心的Mobile工程師,3C愛好者也是書蟲。連絡信箱:tttw216@gmail.com;目前遷移至我的Blog: https://awilab.com/