4889번: 안정적인 문자열
입력은 여러 개의 데이터 세트로 이루어져 있다. 각 데이터 세트는 한 줄로 이루어져 있다. 줄에는 여는 괄호와 닫는 괄호만으로 이루어진 문자열이 주어진다. 문자열의 길이가 2000을 넘는 경우
www.acmicpc.net
괄호가 주어지는대로 그리디하게 해결할 수 있는 문제입니다.
'{'가 주어지면 스택에 바로 push합니다.
'}'일때 스택이 비어있으면 ans에 1을 더하고 방향을 바꿔 '{'로 스택에 push합니다.
스택이 비어있지 않으면 pop을 해주면 됩니다.
이 과정을 반복한 후에 스택이 비어있지 않으면 '{'이 짝수개 남아있다는 말이 됩니다.
그래서 마지막에 s.size()/2를 더해주고 출력합니다.
| 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 50 51 | import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; import java.util.StringTokenizer; public class Main {     static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));     static StringTokenizer st;     static StringBuffer sb = new StringBuffer();     static Stack<Character> s = new Stack<>();     static char ch[];     static int ans = 0;     static void func() {         for (char x : ch) {             if (x == '{') {                 s.push(x);             } else {                 if (s.isEmpty()) {                     ans++;                     s.push('{');                 } else                     s.pop();             }         }         ans += (s.size() / 2);         sb.append(ans + "\n");         ans = 0;         while (!s.isEmpty())             s.pop();     }     static void input() throws Exception {         st = new StringTokenizer(br.readLine());         ch = st.nextToken().toCharArray();     }     public static void main(String[] args) throws Exception {         for (int T = 1;; T++) {             input();             if (ch[0] == '-')                 break;             sb.append(T + ". ");             func();         }         System.out.println(sb.toString());     } } | cs | 
'algorithm > data-structure' 카테고리의 다른 글
| boj 11279 최대 힙 (0) | 2021.01.31 | 
|---|---|
| boj 1927 최소 힙 (0) | 2021.01.31 | 
| boj 2504 괄호의 값 (0) | 2021.01.26 | 
| boj 6198 옥상 정원 꾸미기 (0) | 2021.01.26 | 
| boj 1874 수택 수열 (0) | 2021.01.25 |