๋ฌธ์ ์ ๋ชฉ | ์ ๋ต๋ฅ | ๋์ด๋ |
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
'์๊ณ ๋ฆฌ์ฆ๐ฅ > ๋ฌธ์ ํ์ด (Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 739. daily_temperatures (Medium) 2023/5/9 (0) | 2023.05.09 |
---|---|
[LeetCode] 316. remove_duplicate_letters (Medium) 2023/5/8 (0) | 2023.05.08 |
[LeetCode] 2. Add_Two_Numbers (Medium) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 206. Reverse_Linked_List (Easy) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 21. Merge_Two_Sorted_Lists (Easy) 2023/5/5 (0) | 2023.05.05 |