포스트

[Java] 프로그래머스 - 짝지어 제거하기

For the English version of this post, see here.
[Java] 프로그래머스 - 짝지어 제거하기

Programmers 짝지어 제거하기

풀이

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
import java.util.Stack;

class Solution
{
    public int solution(String s)
    {
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length(); i++) {
            if (stack.isEmpty()) {
                stack.push(s.charAt(i));
            }
            else {
                char ch = s.charAt(i);
                
                if (stack.peek() == ch) {
                    stack.pop();
                }
                else {
                    stack.push(ch);
                }
            }
        }
        
        return stack.isEmpty() ? 1 : 0;

    }
}

Java에서의 Stack 자료구조 사용

  • 주요 메서드
    • push() : 스택에 값을 추가한다.

    • pop() : 스택의 가장 위 값을 제거한다.

    • peek() : 스택의 가장 위 값을 확인한다.

    • isEmpty() : 스택이 비어 있는지 확인한다.