땀두 블로그

[백준] 9012번 - 괄호 본문

알고리즘/백준

[백준] 9012번 - 괄호

땀두 2022. 3. 20. 12:00

 

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

public class p9012 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();

		int a = Integer.parseInt(br.readLine());
		String[] ary = new String[a];

		for (int i = 0; i < a; i++) {
			ary[i] = br.readLine();
		}
		for (int i = 0; i < a; i++) {
			int cnt = 0;
			boolean flag = false;
			for (int j = 0; j < ary[i].length(); j++) {
				if (ary[i].charAt(j) == '(') {
					cnt++;
				} else {
					cnt--;
				}
				if (cnt < 0) {
					flag = true;
				}
			}
			if (cnt == 0 && flag == false) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}
	}
}
 

괄호의 개수를 cnt에 담아 (가 나올때 더해주고 ) 가 나올 때 빼주는 간단한 문제라고 생각했는데 )가 먼저 나오는 경우는 VPS가 성립되지 않기 때문에 이러한 점을 구분하기 위해 flag 변수를 두었고, 이런 경우는 cnt가 음수가 되는 값이므로 조건을 추가해주었다.

 

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 10828번 - 스택  (0) 2022.03.20
[백준] 10773번 - 제로  (0) 2022.03.20
[백준] 1920번 - 수 찾기(HashSet)  (0) 2022.03.20
[백준] 2108번 - 통계학  (0) 2022.03.20
[백준] 1920번 - 수 찾기  (0) 2022.03.20
Comments