๐Ÿ‘ฉโ€๐Ÿ’ป SWEA_1218_๊ด„ํ˜ธ์ง์ง“๊ธฐ

๐Ÿ’ฌ ๊ด„ํ˜ธ์™€ ๊ด€๋ จ๋œ ๊ฒƒ์€ stack..


๐Ÿ’ก ํ’€์ด ๋ฐฉ๋ฒ•

  • ์ž๋ฃŒ๊ตฌ์กฐ ์ค‘ ํ•˜๋‚˜์ธ stack์„ ์‚ฌ์šฉํ•ด ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.
  • ์—ด๋ฆฐ ๊ด„ํ˜ธ๋“ค์€ stack์— ๋„ฃ๊ณ  ๋‹ซํžŒ ๊ด„ํ˜ธ๊ฐ€ ์ž…๋ ฅ๋  ๊ฒฝ์šฐ ๊ธฐ์กด์— ๋„ฃ์–ด์ง„ ์—ด๋ฆฐ ๊ด„ํ˜ธ์™€ ๋น„๊ต๋ฅผ ํ†ตํ•ด์„œ ์ง์ง“๊ธฐ ์—ฌ๋ถ€๋ฅผ ํŒŒ์•…ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ”ฅ ์ฝ”๋“œ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class SWEA_1218_๊ด„ํ˜ธ์ง์ง“๊ธฐ {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		for(int t = 1; t <= 10; t++) {
		Stack<Character> stack = new Stack<>();
		int num = Integer.parseInt(br.readLine());
		String s = br.readLine();
		int flag = 1;
		
		for(int k = 0; k < num; k++) {
			if(s.charAt(k) == '(' || s.charAt(k) == '{' || s.charAt(k) == '[' || s.charAt(k) == '<') {
				stack.push(s.charAt(k));
			}
			else {
				if(stack.size() == 0) {
					flag = 0;
					break;
				}
				else {
					char tmp = stack.pop();
					if((s.charAt(k) == ')' && tmp == '(' )|| (s.charAt(k) == '}' && tmp == '{')
				|| (s.charAt(k) == ']' && tmp == '[') || (s.charAt(k) == '>' && tmp == '<')) {
						flag = 1;
						continue;
					}
					else {
						flag = 0;
						break;
					}
				}
			}			
		}
		System.out.println("#" + t + " " + flag);
		}
	}

}

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ