Skip to content

Commit 6fc81e6

Browse files
committed
add valid parentheses solution
1 parent 5caf65c commit 6fc81e6

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

valid-parentheses/Tessa1217.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* 유효한 괄호: '(', ')', '{', '}', '[', ']'로 이루어진 문자열 s가 주어질 때 문자열 s가 유효한 괄호로 이루어진 문자열인지 판별하세요.
3+
유요한 문자열인지의 판별 방법
4+
1. 여는 괄호는 반드시 같은 종류의 닫는 괄호에 의해 닫혀야 한다.
5+
2. 여는 괄호는 반드시 정확한 순서로 닫혀야 한다.
6+
3. 모든 닫는 괄호는 같은 종류의 여는 괄호에 의해서 열려야 한다.
7+
*/
8+
class Solution {
9+
10+
// 시간복잡도: O(n)
11+
public boolean isValid(String s) {
12+
13+
Stack<Character> parentheses = new Stack<>();
14+
// 맵으로 조건문 간소화
15+
Map<Character, Character> parenthesisMap = Map.of(')', '(', '}', '{', ']', '[');
16+
17+
for (char c : s.toCharArray()) {
18+
if (c == '(' || c == '{' || c == '[') {
19+
parentheses.push(c);
20+
} else if (parentheses.isEmpty() || parentheses.pop() != parenthesisMap.get(c)) { // 전체 다 돌지 않고 유효한 괄호 아니면 사전에 불린 반환
21+
return false;
22+
}
23+
}
24+
25+
return parentheses.size() == 0;
26+
27+
}
28+
29+
// public boolean isValid(String s) {
30+
31+
// Stack<Character> parentheses = new Stack<>();
32+
// // 맵으로 조건문 간소화
33+
// Map<Character, Character> parenthesisMap = Map.of(')', '(', '}', '{', ']', '[');
34+
35+
// for (char c : s.toCharArray()) {
36+
// if (parentheses.isEmpty()) {
37+
// parentheses.push(c);
38+
// continue;
39+
// }
40+
// if (parentheses.peek() == parenthesisMap.get(c)) {
41+
// parentheses.pop();
42+
// } else {
43+
// parentheses.push(c);
44+
// }
45+
// }
46+
47+
// return parentheses.size() == 0;
48+
49+
// }
50+
51+
// public boolean isValid(String s) {
52+
53+
// Stack<Character> parentheses = new Stack<>();
54+
55+
// for (char c : s.toCharArray()) {
56+
// if (parentheses.isEmpty()) {
57+
// parentheses.push(c);
58+
// continue;
59+
// }
60+
// if ((parentheses.peek() == '(' && c == ')') ||
61+
// (parentheses.peek() == '{' && c == '}') ||
62+
// (parentheses.peek() == '[' && c == ']')) {
63+
// parentheses.pop();
64+
// } else {
65+
// parentheses.push(c);
66+
// }
67+
// }
68+
69+
// return parentheses.size() == 0;
70+
71+
// }
72+
}
73+

0 commit comments

Comments
 (0)