본문 바로가기
알고리즘 & 자료구조/프로그래머스

짝지어 제거하기

by 신재권 2023. 1. 3.
package programmers;

import java.util.Stack;

public class 짝지어제거하기 {

   public static int solution(String s) {
      Stack<Character> stack = new Stack<>();
      int idx = 0;

      if (s.length() == 0) {
         return 0;
      }

      stack.push(s.charAt(idx++));
      while (idx < s.length()) {
         char c = s.charAt(idx++);

         if (!stack.isEmpty() && stack.peek() == c) {
            stack.pop();
         } else {
            stack.push(c);
         }

      }

      return stack.isEmpty() ? 1 : 0;
   }

   public static void main(String[] args) {
      // System.out.println(solution("baabaa"));
      // System.out.println(solution("cdcd"));
      // System.out.println(solution(""));
      // System.out.println(solution("a"));
      System.out.println(solution("aaaaa"));


   }
}

'알고리즘 & 자료구조 > 프로그래머스' 카테고리의 다른 글

구명 보트  (0) 2023.01.05
영어 끝말잇기  (0) 2023.01.04
카펫  (0) 2023.01.02
다음 큰 숫자  (0) 2023.01.01
피보나치 수  (0) 2022.12.31