Skip to content

Commit 17b7837

Browse files
committed
[week2] solve 20. Valid Parentheses
1 parent bfd7843 commit 17b7837

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

โ€Žvalid-parentheses/bky373.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* - ๋ฌธ์ œ: https://leetcode.com/problems/valid-parentheses/
3+
* - TC: O(N)
4+
* - SC: O(1)
5+
*/
6+
class Solution_20 {
7+
8+
public boolean isValid(String s) {
9+
Stack<Character> st = new Stack<>();
10+
Map<Character, Character> pairs = Map.of('(', ')', '{', '}', '[', ']');
11+
12+
for (int i = 0; i < s.length(); i++) {
13+
// ์—ด๋ฆฐ ๊ด„ํ˜ธ์ด๋ฉด ์Šคํƒ์— push
14+
if (pairs.containsKey(s.charAt(i))) {
15+
st.push(s.charAt(i));
16+
} else { // ๋‹ซํžŒ ๊ด„ํ˜ธ์ธ๋ฐ
17+
if (st.isEmpty()) { // ์Šคํƒ์ด ๋น„์–ด์žˆ์œผ๋ฉด(์—ด๋ฆฐ ๊ด„ํ˜ธ๊ฐ€ ์—†์œผ๋ฉด) false ๋ฐ˜ํ™˜
18+
return false;
19+
}
20+
// ์Šคํƒ์˜ ์ตœ๊ทผ ์š”์†Œ(์—ด๋ฆฐ ๊ด„ํ˜ธ)์™€ ์ง์„ ์ด๋ฃจ์ง€ ์•Š์œผ๋ฉด false ๋ฐ˜ํ™˜
21+
if (s.charAt(i) != pairs.get(st.pop())) {
22+
return false;
23+
}
24+
}
25+
}
26+
// ์—ด๋ฆฐ ๊ด„ํ˜ธ๊ฐ€ ๋‚จ์•„ ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋ชฉ๋ก์ด ๋น„์–ด์žˆ๋Š”์ง€ ์ฒดํฌ
27+
return st.isEmpty();
28+
}
29+
}

0 commit comments

Comments
ย (0)