문제 출처: https://www.acmicpc.net/problem/9012
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 46 47 48 49 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class algo4_9012_parenthesis_string { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder builder = new StringBuilder(); Integer T = Integer.parseInt(reader.readLine()); for(int i=0 ; i<T ; i++){ if(validPS(reader.readLine())) builder.append("YES\n"); else builder.append("NO\n"); } System.out.println(builder); } public static boolean validPS(String psStr){ boolean isValid = false; Stack<Character> stack = new Stack<>(); int position = psStr.length()-1; stack.push(psStr.charAt(position)); for(--position ; position>=0 ; position--){ char ps = psStr.charAt(position); if(stack.isEmpty() || ps==stack.peek()) stack.push(ps); else if(ps==')' && stack.peek()=='(') stack.push(ps); else stack.pop(); } if(stack.isEmpty()) isValid = true; else isValid = false; return isValid; } } | cs |
'Algorithm' 카테고리의 다른 글
백준 1874번: 스택 수열 (0) | 2018.07.23 |
---|---|
백준 10799번: 쇠막대기 (0) | 2018.07.20 |
백준 10828번: 스택 (0) | 2018.07.17 |
백준 1260번: DFS와 BFS (0) | 2018.04.18 |
BFS (Breadth-First Search) (0) | 2018.04.12 |