Skip to content

Commit 74baff6

Browse files
committed
[yapp][mand2] 20.valid-parentheses
1 parent bdb5680 commit 74baff6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

โ€Žvalid-parentheses/mand2.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
### Intuition
2+
- opening(`([{`) ์Šคํƒ์„ ์Œ“๋Š”๋‹ค.
3+
- ๋น„๊ตํ•œ๋‹ค.
4+
5+
### Approach
6+
1. ๋จผ์ € ์ž…๋ ฅ๋ฐ›์€ ๊ธ€์ž์˜ ๊ธธ์ด๊ฐ€ ์ง์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฉด ๋ฌด์กฐ๊ฑด **False**.
7+
2. for ๋ฌธ
8+
- opening(`([{`) ์ด๋ฉด stack ์— ๋„ฃ๋Š”๋‹ค.
9+
- stack ์ด ๋น„์–ด์žˆ๊ฑฐ๋‚˜, ์ง์ด ๋งž์ง€ ์•Š์œผ๋ฉด(`is_parentheses()==False`) **False**.
10+
3. ๋‹ค ์™„๋ฃŒ๋˜๊ณ  ๋‚˜์„œ, ์Šคํƒ์ด ๋น„์–ด์žˆ๋‹ค๋ฉด **True**.
11+
12+
13+
### Complexity
14+
- Time complexity: O(n)
15+
- Space complexity: O(n)
16+
17+
18+
### Code
19+
20+
```python
21+
class Solution:
22+
def isValid(self, s: str) -> bool:
23+
stack = []
24+
if len(s) % 2 != 0:
25+
return False
26+
for word in s:
27+
if word in '([{':
28+
stack.append(word)
29+
elif not stack or is_parentheses(stack.pop(), word) is False:
30+
return False
31+
return not stack
32+
33+
34+
def is_parentheses(pointer, word) -> bool:
35+
if pointer == '(' and word == ')':
36+
return True
37+
elif pointer == '[' and word == ']':
38+
return True
39+
elif pointer == '{' and word == '}':
40+
return True
41+
else: return False
42+
```

0 commit comments

Comments
ย (0)