# BOJ01316 그룹 단어 체커

https://www.acmicpc.net/problem/1316 (opens new window)

그룹 단어란? 단어에 존재하는 모든 문제에 대해서, 각 문자가 연속해서 나타나는 경우이다. 하지만 aabbbccb의 경우 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다.

아래는 그룹 단어인지 체크하기 위한 isGroupWord 메소드이다.

private static boolean isGroupWord(String word) {
    List<Character> alphabets = new ArrayList<>();

    alphabets.add(word.charAt(0));
    char prev = word.charAt(0);
    for (int i = 1; i < word.length(); i++) {
        if (prev == word.charAt(i)) { // 연속해서 나타나는 경우 계속 진행한다.
            continue;
        // 연속하지 않지만 이전에 등장한 알파벳인 경우 그룹 단어가 아니다.
        } else if (prev != word.charAt(i) 
                && alphabets.contains(word.charAt(i))) {
            return false;
        }
        prev = word.charAt(i);
        alphabets.add(word.charAt(i));
    }
    
    return true;
}

아래는 전체 코드이다.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BOJ1316 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        scanner.nextLine();

        int count = 0;
        for (int i = 0; i < n; i++) {
            String word = scanner.nextLine();
            if (isGroupWord(word)) {
                count++;
            }
        }

        System.out.println(count);
    }

    private static boolean isGroupWord(String word) {
        List<Character> alphabets = new ArrayList<>();

        alphabets.add(word.charAt(0));
        char prev = word.charAt(0);
        for (int i = 1; i < word.length(); i++) {
            if (prev == word.charAt(i)) {
                continue;
            } else if (prev != word.charAt(i) 
                    && alphabets.contains(word.charAt(i))) {
                return false;
            }

            prev = word.charAt(i);
            alphabets.add(word.charAt(i));
        }

        return true;
    }
}
#algorithm #BOJ #구현 #문자열
last updated: 10/10/2021, 6:09:25 PM