https://www.acmicpc.net/problem/4949
풀이
어렵게 생각하면 어렵고 쉽게 생각하면 쉬운 문제였다.
많은 문자열을 입력받지만, 우리가 생각해야될 것은 괄호 뿐이므로 '(', ')', '[', ']'가 들어오는 경우만
생각해주면 된다.
'(' , '['이 들어오는 경우는 Stack에 Push 하였고
')', ']' 이 들어오는 경우는 앞에 여는 괄호가 일치한지만 판단하여 pop하였다.
기타
풀다가 문자열을 비교할 때 equals 와 == 차이가 궁금해서 글로 한번 요약 정리 해보았다.
https://studywithus.tistory.com/88
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] agrs) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while (true) {
String input = br.readLine();
if (input.equals("."))
break;
sb.append(solve(input) + '\n');
}
System.out.println(sb);
}
static String solve(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '(' || c == '[')
stack.push(c);
if (c == ')') {
if (stack.isEmpty() || stack.peek() != '(')
return "no";
else
stack.pop();
}
if (c == ']') {
if (stack.isEmpty() || stack.peek() != '[')
return "no";
else
stack.pop();
}
}
if (stack.isEmpty())
return "yes";
else
return "no";
}
}
'프로그래밍 & IT > Algorithm' 카테고리의 다른 글
[알고리즘] 백준 4963번 섬의개수 :: 우유 (0) | 2022.06.19 |
---|---|
[알고리즘] 백준 11047번 동전 0 :: 우유 (0) | 2022.06.09 |
[알고리즘] 백준 2477번 참외밭 :: 우유 (0) | 2022.06.09 |
[알고리즘] 백준 7562번 나이트의 이동 :: 우유 (0) | 2022.04.18 |
[알고리즘] 백준 2206번 벽 부수고 이동하기 :: 우유 (0) | 2022.04.17 |