문제보기 >> 1218. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기


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
43
44
45
import java.util.Scanner;
import java.util.Stack;
 
public class Solution_1218_괄호짝짓기{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        for(int tc = 1; tc <=10;tc++) {
            int result = -1;
            int len = sc.nextInt();
 
            String str = sc.next();
            Stack s = new Stack();
            
            for(int i=0;i<len;i++) {
                if(str.charAt(i) == '(' || str.charAt(i) == '{' || str.charAt(i) == '[' || str.charAt(i) == '<' ) s.push(str.charAt(i));
                else if(str.charAt(i) == ')' || str.charAt(i) == '}' || str.charAt(i) == ']' || str.charAt(i) == '>') {
//                    if(s.isEmpty()){
//                        result = 0;
//                        break;
//                    }
                    char pop = (char) s.pop();
                    if ( (str.charAt(i) == ')' && pop =='(' ) 
                        || (str.charAt(i) == '}' && pop =='{' )
                        || (str.charAt(i) == ']' && pop =='[')
                        || (str.charAt(i) == '>' && pop =='<')) {
                        continue;
                    }else {
                        result = 0;
                    }
                    
                }
                if(result ==0 )break;
            }
            if(s.size() != 0) result = 0;
            else result = 1;
            
            
            System.out.println("#"+tc+" "+result);
            
            
        }
    }
}
 
cs


+ Recent posts