CS/코딜리티

문제 // Codility // Stacks and Queues // Brackets

문스코딩 2018. 8. 23. 12:35
업데이트 :: 2018.08.23



문제

Stacks and Queues > Brackets
Determine whether a given string of parentheses (multiple types) is properly nested.

코드

1차 풀이

import java.util.*;
class Solution {
    public int solution(String S) {
        if(S.equals("")) return 1;
        int count = 0;
        int flag = 0; // () 0, {} 1, [] 2 
        Stack<Integer> stack = new Stack<Integer>();
        for(int i=0; i<S.length(); i++) {
            switch(S.charAt(i)) {
                case '(':
                    stack.push(0);
                    break;
                case '{':
                    stack.push(1);
                    break;
                case '[':
                    stack.push(2);
                    break;
                case ')':
                    if(stack.size() > 0) {
                        if(stack.pop() != 0) return 0;
                    } else return 0;
                    break;
                case '}':
                    if(stack.size() > 0) {
                        if(stack.pop() != 1) return 0;
                    } else return 0;
                    break;
                case ']':
                    if(stack.size() > 0) {
                        if(stack.pop() != 2) return 0;
                    } else return 0;
                    break;
            }
        }
        return stack.size() == 0 ? 1 : 0;
    }
}

2차 풀이

class Solution {
    public int solution(String S) {
        if(S.equals("")) return 1;
        int stack = 0;
        for(int i=0; i<S.length(); i++) {
            if(S.charAt(i) == '(') {
                stack++;
            } else {
                stack--;
                if(stack < 0) return 0;
            }
        }
        return (stack == 0) ? 1 : 0;
    }
}

결과

1차 100%

  • 정확 : 100%
  • 성능 : 100%

Created by MoonsCoding

e-mail :: jm921106@gmail.com

반응형