본문 바로가기

알고리즘 풀이(JAVA)/백준

[백준] 문제번호 3986 (좋은 단어)(java)

<문제 3986 - 좋은단어>

 

[문제]

 

* 이런식으로, 선이 겹치면 좋은단어가 아니고 선이 안겹치고 짝이 지어진다면 좋은단어라고 판별

 

<답안>

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int cnt = 0; // '좋은단어' 의 갯수 찾기 용도
        String str;

        int n = Integer.parseInt(sc.nextLine()); // 단어의 수 n개 받기

        for (int i = 0; i < n; i++) {
            Stack<Character> stack = new Stack<>();
            str = sc.nextLine(); // 단어의 수 만큼 문자 입력받기

            for (int j = 0; j < str.length(); j++) {
                if (stack.isEmpty()){ // 만약 stack이 비어있으면
                    stack.push(str.charAt(j));  // push로 값 넣기
                }else if (stack.peek().equals(str.charAt(j))){ // stack에 들어간 마지막 데이터가 들어온 데이터와 같은 문자라면
                    stack.pop(); // pop으로 데이터 제거
                }else {
                    stack.push(str.charAt(j)); // 그렇지 않으면 추가
                  }
                }
            if (stack.isEmpty()){ // 만약 위 과정을 거치고 stack이 비어있으면?
                cnt++; // 카운트 증가
            }
        }
        System.out.println(cnt); // 최종 카운트 값 출력
    }
}