포스트

[Java] Programmers - pair removal

한국어 원문은 여기에서 볼 수 있습니다.
[Java] Programmers - pair removal

Programmers 짝지어 제거하기

Solution

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;

    }
}

Use of Stack data structure in Java

  • Main method
    • push(): Adds a value to the stack.

    • pop(): Removes the top value of the stack.

    • peek(): Check the top value of the stack.

    • isEmpty(): Check whether the stack is empty.