1316 그룹 단어 체커

 

코드

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            if(groupWord(sc.next())) cnt++;
        }
        System.out.println(cnt);
    }

    private static boolean groupWord(String word) {
        boolean[] visited = new boolean[26];
        for (int i = 0; i < word.length(); i++) {
            if(!visited[word.charAt(i) - 'a']){ // 처음 나오는 알파벳
                visited[word.charAt(i) - 'a'] = true;
            }
            else if(word.charAt(i-1)!=word.charAt(i)){ // 이전에 나온적 있음 + 전 글자와 연속되지 않음
                return false;
            }
        }
        return true;
    }
}

 

코드 설명

  1. 입력 받을 단어 개수를 n수에 입력받는다.
  2. groupWord함수에 새로 입력받는 단어를 인자로 받아, true라면 cnt값을 1씩 증가시킨다 (n번 반복)
    • for문을 통해 문자열을 순회하며 각 문자의 등장 여부를 확인한다
      • 현 문자가 처음 나온 경우, visited[현 문자] = true를 할당한다
      • 현 문자가 이전에 나왔으며, 직전 문자와 다른 경우, return false
  3. 최종 cnt값을 출력한다

 

 

실행 결과

 

 

'Algorithm > BOJ' 카테고리의 다른 글

[BOJ] 1546 평균  (0) 2023.10.03
[BOJ] 25206 너의 평점은  (0) 2023.09.30
[BOJ] 10988 팰린드롬인지 확인하기  (0) 2023.09.30
[BOJ] 1629 곱셈  (0) 2022.11.20
[BOJ] 5619 세 번째  (0) 2022.11.20

+ Recent posts