알고리즘/백준
코딩공부 77일차: 백준 9012번 괄호 자바 Java
김발자~
2022. 10. 17. 16:18
반응형
9093 단어 뒤집기
https://www.acmicpc.net/problem/9012
9012번: 괄호
괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고
www.acmicpc.net
백준 9012번 문제 괄호
문제
과정 생각해보기
https://gimbalja.tistory.com/m/138
여기서 보았던 자바의 정석 예제를 활용하기로 했다
괄호의 짝이 맞는 걸 묻는 문제라 본질이 같았다
오답
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Character> st = new Stack();
int t = Integer.parseInt(br.readLine());
for(int i = 0; i < t; i++) {
try {
String str = br.readLine();
for(int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
if(ch == '(') {
st.push(ch);
}else if (ch == ')'){
st.pop();
}
}
if(st.empty())
System.out.println("YES");
else
System.out.println("NO");
}
catch(Exception e){
System.out.println("NO");
}
}
}
}
|
cs |
그래서 try catch문을 활용해 적어봤는데 마음대로 되지 않았다
정답 인정 코드
카카오 이슈로 티스토리가 되지 않아서 확인해볼 수 있는 자료가 많지 않았다
하지만 위 블로그는 티스토리가 아니라서 참고할 수 있었다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Character> st = new Stack();
int t = Integer.parseInt(br.readLine());
for(int i = 0; i < t; i++) {
String str = br.readLine()+"\n";
for(int j = 0; j < str.length();j++) {
char ch = str.charAt(j);
if(ch == '(') {
st.push(ch);
}else if(ch == ')') {
if(st.empty()) {
st.push(ch); //얘 없이 break하면 "YES"됨
break;
}else
st.pop();
}
}
if(st.empty()) {
System.out.println("YES");
}else {
System.out.println("NO");
}
st.clear();
}
}
}
|
cs |
try catch문보다 훨씬 직관적이라 가독성도 좋다고 느꼈다
https://cokes.tistory.com/m/98
try catch문을 사용하고 싶다면이 블로그를 참조하면 될 것 같다
반응형