알고리즘 및 자료구조/문제
algospot 괄호2(Mismatched Brackets)
ktko
2016. 3. 23. 23:05
()() ({[}]) ({}[(){}])
open-close괄호 미스매치를 확인하는 문제이다.
Stack을 이용한 문제이고
{[(와 같은 여는 괄호일 경우 스택에 저장한다
}])와 같이 닫는 괄호가 나올 경우 괄호에 맞는 여는괄호가 나오는지 확인하면 된다.
package com.ktko.Success; import java.util.Scanner; import java.util.Stack; public class MismatchedBrackets { static int testCase; static String test; static int result[]; static Stack stack; public static void main(String[] args) { // TODO Auto-generated method stub stack = new Stack<Object>(); Scanner scan = new Scanner(System.in); testCase = Integer.parseInt(scan.nextLine()); // 테스트 케이스 result = new int[testCase]; for (int i = 0; i < testCase; i++) { test = scan.nextLine().trim(); result[i] = calMismatched(test); } for (int i = 0; i < testCase; i++) { if (result[i] != 0) System.out.println("NO"); else System.out.println("YES"); } } public static int calMismatched(String test) { stack.clear(); if (test.length() % 2 != 0) return -1; String openString = "({["; char[] charArray = test.toCharArray(); for (int i = 0; i < charArray.length; i++) { if (openString.indexOf(charArray[i]) > -1) { stack.push(charArray[i]); } else { if (stack.empty()) { return -1; } if (charArray[i] == '}') { if((char)stack.pop() == '{') continue; else return -1; } if (charArray[i] == ']') { if((char)stack.pop() == '[') continue; else return -1; } if (charArray[i] == ')') { if((char)stack.pop() == '(') continue; else return -1; } } } if(!stack.isEmpty()) return -1; return 0; } }