[알고리즘/SWEA] #1218 괄호 짝짓기

JudyLia·2022년 2월 7일
0

알고리즘

목록 보기
20/61
post-thumbnail
  • stack을 사용 안 함
package algorithm_lab.day03.q2;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

public class Solution {
	
	//stack 사용 없이
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		System.setIn(new FileInputStream("./src/algorithm_lab/day03/q2/input.txt"));
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		
		for(int T=1;T<=10;T++) {
			
			int size=Integer.parseInt(br.readLine());
			String[] s = br.readLine().split("");
			ArrayList<String> list=new ArrayList<String>();
			int answer=1;
			for(String temp : s){
				list.add(temp);
			}
			int big_open=Collections.frequency(list, "[");
			int big_close=Collections.frequency(list, "]");
			int mid_open=Collections.frequency(list, "{");
			int mid_close=Collections.frequency(list, "}");
			int small_open=Collections.frequency(list, "(");
			int small_close=Collections.frequency(list, ")");
			int open=Collections.frequency(list, "<");
			int close=Collections.frequency(list, ">");
			
			if(big_open!=big_close) {
				answer=0;
			}
			if(open!=close) {
				answer=0;
			}
			if(mid_open!=mid_close) {
				answer=0;
			}
			if(small_open!=small_close) {
				answer=0;
			}
			
			StringBuilder sb = new StringBuilder();
			sb.append("#").append(T).append(" ").append(answer).append("\n");
			System.out.print(sb.toString());
		}
	}
}
  • stack 사용
package day03_0207.ws;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;

public class Solution_1218_괄호짝짖기 {

	static int N, Res;
	static Stack<Character> stack = new Stack<Character>(); //선언 위치에 따라 초기화및 클리어 처리 필요
	static Map<Character, Character> map = new HashMap<Character, Character>();

	public static void main(String[] args) throws Exception {
		System.setIn(new FileInputStream("input/1218.txt"));
		Scanner sc = new Scanner(System.in);

		map.put('}', '{');
		map.put(')', '(');
		map.put('>', '<');
		map.put(']', '[');

		for (int t = 1; t <= 10; t++) {
			Res = 1;
			N = sc.nextInt();
			String msg = sc.next().trim();
			if(msg.length() % 2 == 1) {
				Res = 0;
			}else {
				for(int i=0;i<msg.length();i++) {
					char ch = msg.charAt(i);
					if(ch=='{'||ch=='('||ch=='<'||ch=='[') {
						stack.push(ch);
					}else {
						//if(stack.isEmpty() || stack.pop() != map.get(ch)) {
						if(stack.isEmpty() || !stack.pop().equals(map.get(ch))) {
							Res = 0;
							break;
						}
					}
				}
				if(!stack.isEmpty()) Res=0;
			}

			System.out.printf("#%d %s%n", t, Res);
			stack.clear(); //주의한다.
		}
	}
}
profile
안녕:)

0개의 댓글

관련 채용 정보