Dev.baelanche

[백준 4949] 균형잡힌 세상 본문

Data Structure & Algorithm/PS - JAVA

[백준 4949] 균형잡힌 세상

baelanche 2019. 6. 29. 17:24
반응형

 

문자열에서 (, ), [, ] 말고는 신경쓰지 않는다.

 

1. (, [ 문자는 스택에 바로 담는다.

2. ) 문자는 스택의 top이 (이면 둘이 합쳐서 pop한다.

2-1. ] 문자는 스택의 top이 [이면 둘이 합쳐서 pop한다.

3. ), ] 문자가 들어왔을때 스택이 비어있거나 탑이 자신의 쌍이 아니면 균형이 안잡힌 문자열이다.

4. 문자열 점검이 끝났을때 스택이 비어있어야 한다.

 

public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while(true) {
            String str = sc.nextLine();
            if(str.equals(".")) break;
            
            Stack<Character> s = new Stack();
            
            boolean b = true;
            for(int i=0; i<str.length(); i++) {
                if(s.isEmpty() && (str.charAt(i) == ')' || str.charAt(i) == ']')) {
                    b = false;
                    break;
                }
                if(str.charAt(i) == '(') s.push('(');
                if(str.charAt(i) == ')') {
                    if(s.peek() == '(') s.pop();
                    else s.push(')');
                }
                if(str.charAt(i) == '[') s.push('[');
                if(str.charAt(i) == ']') {
                    if(s.peek() == '[') s.pop();
                    else s.push(']');
                }
            }
            if(s.isEmpty() && b) System.out.println("yes");
            else System.out.println("no");
        }
    }
}
반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 6603] 로또  (0) 2019.06.29
[백준 11866] 조세퍼스 문제 0  (0) 2019.06.29
[백준 10773] 제로  (0) 2019.06.29
[백준 15685] 드래곤 커브  (0) 2019.06.29
[백준 11729] 하노이 탑 이동 순서  (0) 2019.06.25
Comments