백준 1316번: 그룹 단어 체커

hoon·2025년 1월 24일

백준

목록 보기
26/44

https://www.acmicpc.net/problem/1316

import java.util.Scanner;

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

        int n = scanner.nextInt(); // 단어의 개수 입력
        int groupWordCount = 0;

        for (int i = 0; i < n; i++) {
            String word = scanner.next(); // 단어 입력
            if (isGroupWord(word)) {
                groupWordCount++;
            }
        }

        System.out.println(groupWordCount); // 그룹 단어의 개수 출력
        scanner.close();
    }

    // 그룹 단어인지 확인하는 메서드
    public static boolean isGroupWord(String word) {
        boolean[] seen = new boolean[26]; // 알파벳 등장 여부 확인 배열
        char prevChar = '\0'; // 이전 문자 초기화

        for (char c : word.toCharArray()) {
            if (c != prevChar) { // 이전 문자와 다른 경우
                if (seen[c - 'a']) { // 이미 등장한 문자라면 그룹 단어가 아님
                    return false;
                }
                seen[c - 'a'] = true; // 처음 등장한 문자로 표시
                prevChar = c; // 이전 문자 갱신
            }
        }

        return true; // 모든 조건을 통과하면 그룹 단어
    }
}

0개의 댓글