์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 20. Valid_Parentheses (Easy) 2023/5/8

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 8. 18:30
728x90
๋ฌธ์ œ ์ œ๋ชฉ ์ •๋‹ต๋ฅ  ๋‚œ์ด๋„
20. Valid_Parentheses 40.5% Easy
 

Valid Parentheses - LeetCode

Can you solve this real interview question? Valid Parentheses - 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 sam

leetcode.com

 

๋ฌธ์ œ์š”์•ฝ

๋ฌธ์ž์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ์ž…๋ ฅ๊ฐ’์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํŒ๋‹จํ•˜๋ผ

์กฐ๊ฑด 1) ๋ฌธ์ž์—ด์€ ์†Œ๊ด„ํ˜ธ (), ์ค‘๊ด„ํ˜ธ {}, ๋Œ€๊ด„ํ˜ธ []๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋‹ค

์กฐ๊ฑด 2) ์—ด๋ฆฐ ๊ด„ํ˜ธ๋“ค์€ ๊ฐ™์€ ์ข…๋ฅ˜์˜ ๋‹ซํžŒ ๊ด„ํ˜ธ์™€ ์˜ฌ๋ฐ”๋ฅธ ์ˆœ์„œ๋กœ ๋งค์นญ๋˜์–ด์•ผ ํ•œ๋‹ค.

์กฐ๊ฑด 3) ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ์ด๊ณ , ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ์ฐธ์ด๋‚˜ ๊ฑฐ์ง“์„ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค

 

 

ํ’€์ด 1

์Šคํƒ์„ ์ด์šฉ

Step1. ์—ด๋ฆฐ๊ด„ํ˜ธ, ๋‹ซํžŒ๊ด„ํ˜ธ ๋งค์น˜ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•ด ๋”•์…”๋„ˆ๋ฆฌ ์ด์šฉ

 

Step2. ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž์— ๋Œ€ํ•ด ํŒ๋‹จ

  • ์—ด๋ฆฐ ๊ด„ํ˜ธ์ด๋ฉด ์Šคํƒ์— ์‚ฝ์ž…
  • ๋‹ซํžŒ ๊ด„ํ˜ธ์ด๋ฉด ๋ฐ”๋กœ ์Šคํƒ.top์ด๋ž‘ ๋งค์น˜๋˜๋Š”์ง€ ํ™•์ธ
    • ์Šคํƒ ๊ธธ์ด๊ฐ€ 0์ด๊ฑฐ๋‚˜, ๋งค์น˜๋˜์ง€ ์•Š์œผ๋ฉด ๊ฑฐ์ง“ ๋ฐ˜ํ™˜

 

Step3. return ๊ฐ’ ์ตœ์ ํ™”

  • ์Šคํƒ๊ธธ์ด๊ฐ€ 0์ด์—ฌ์•ผ ์ฐธ ๊ฐ’์„ ๋ฐ˜ํ™˜, ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด ๊ฑฐ์ง“์„ ๋ฐ˜ํ™˜ํ•˜๋Š”๋ฐ
  • ์ด๋•Œ, if ๊ตฌ๋ฌธ์„ ์ด์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค, return์—์„œ ๋ฐ”๋กœ ํŒ๋‹จํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒŒ ์•ฝ 10ms ๊ฐ€๋Ÿ‰ ์‹œ๊ฐ„ ์ ˆ์•ฝ

 

 

๊ตฌํ˜„ (43ms)

class Solution:
    def isValid(self, s: str) -> bool:
        stack=[]
        parentheses_dict={'(':')', '{':'}', '[':']'}
        for char in s:
            if char in ['(', '{', '[']:
                stack.append(char)
            elif len(stack)==0 or parentheses_dict[stack.pop()]!=char:
                return False
            else:
                continue
        return len(stack)==0
728x90