올바른 괄호

최준호·2021년 8월 22일
0

알고리즘 강의

목록 보기
28/79

설명

괄호가 입력되면 올바른 괄호이면 “YES", 올바르지 않으면 ”NO"를 출력합니다.

(())() 이것은 괄호의 쌍이 올바르게 위치하는 거지만, (()()))은 올바른 괄호가 아니다.

코드

public class CorrectString {
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        String input1 = in.next();

        String solution = solution(input1);
        System.out.println(solution);
    }
    public static String solution(String s){
        Stack<String> stack = new Stack<>();
        char[] chars = s.toCharArray();
        for(char c : chars){
            if(c=='(') stack.push("(");
            else if(c==')'){
                if(stack.isEmpty()) return "NO";
                stack.pop();
            }
        }

        if(!stack.isEmpty()) return "NO";
        return "YES";
    }
}

stack의 대표 문제 쉬웠음.

하지만 꼭 기억해야할 것으로 Stack이 비어있을 때 pop을 하게되면 runtimeError가 발생하므로 꼭 pop하기 전에 stack이 비어있는지 확인하고 pop을 하도록 하자!

profile
코딩을 깔끔하게 하고 싶어하는 초보 개발자 (편하게 글을 쓰기위해 반말체를 사용하고 있습니다! 양해 부탁드려요!) 현재 KakaoVX 근무중입니다!

0개의 댓글