티스토리 뷰

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/12909

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


[for 문 사용]

Point. 괄호 개수를 세는 것이 아니라 (는 count +1, )는 count -1 의 개념으로 접근한다. 마지막 count는 항상 0이고, count가 마이너스가 되는 순가 무조건 틀린답이다.

class Solution {  
    boolean solution(String s) {
        int count = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') {
                count ++;
            }

            if(s.charAt(i) == ')') {
                count --;
            }

            if(count < 0) {
                return false;
            }
        }

        if(count != 0) {
            return false;
        }

        return true;
    }
}

[Stack 사용]

Point. 동일하게 개수가 아닌 pop, push를 사용하되, empty를 이용한다. 마지막은 항상 empty이고, for문 도중 empty가 되는 것은 틀린답이다.

import java.util.Stack;

class Solution {  
    boolean solution(String s) {
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') {
                stack.push(i);
            }

            if(s.charAt(i) == ')') {
                if(stack.isEmpty()) {
                    return false;
                }else {
                    stack.pop();
                }
            }
        }

        if(!stack.isEmpty()) {
            return false;
        }

        return true;
    }
}
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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