BOJ_S4_4949
π [S4_4949] κ· νμ‘ν μΈμ
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));
StringBuilder sb = new StringBuilder();
boolean check = true;
while (check) {
String str = br.readLine();
// μ’
λ£ μ‘°κ±΄
if (str.equals(".")) {
check = false;
} else {
String res = check(str);
sb.append(res).append("\n");
}
}
System.out.println(sb);
}
// Stackμ μ΄μ©ν΄ λ¬Έμκ° κ· νμ‘ν λ¬Έμμ΄μΈμ§ 체ν¬
static String check(String str) {
String res = "yes";
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
// μμλΆλΆ
if (str.charAt(i) == '[' || str.charAt(i) == '(') {
stack.add(str.charAt(i));
}
// λκ΄νΈ λ«ν
if (str.charAt(i) == ']') {
if (stack.size() == 0) {
res = "no";
break;
}
char pop = stack.pop();
if (pop != '[') {
res = "no";
break;
}
}
// μκ΄νΈ λ«ν
if (str.charAt(i) == ')') {
if (stack.size() == 0) {
res = "no";
break;
}
char pop = stack.pop();
if (pop != '(') {
res = "no";
break;
}
}
}
// λ§λ¬΄λ¦¬κ° μλκ²½μ° no
if(stack.size()>0) res="no";
return res;
}
}
π€ λμ μκ°
Stackμ μ¬μ©νλ λ¬Έμ μ΄λ€.
- β[β κ³Ό β(β μ΄λ©΄ stackμ add
- stackμ μ무κ²λ μλλ° λ«ν κ²½μ° no
- β]β μΌλ stackμμ pop ν κ²μ΄ β[β μ΄λ©΄ ν΅κ³Ό, μλλ©΄ no
- β)β μΌλ stackμμ pop ν κ²μ΄ β(β μ΄λ©΄ ν΅κ³Ό, μλλ©΄ no
- λ§μ§λ§μ stackμ κ°μ΄ λ¨μμμΌλ©΄ no ( μμ±μ΄ μλ κ²½μ° )
빨리 λ¬Έμ λ₯Ό νκ³ μ€νμ μ무κ²λ μλ κ²½μ°μ λ§μ§λ§ μμ±μ΄ μλ κ²½μ°λ₯Ό λμ³μ μκ°μ΄ μ’ κ±Έλ Έλ€.