본문 바로가기

알고리즘/백준

[백준] 1316 - 그룹 단어 체커 (JAVA/ 자바)

반응형

1316번 문제(1)
1316번 문제(2)

 

1. Scanner를 이용한 방법

import java.util.Scanner;

public class Main{
    static Scanner sc = new Scanner(System.in);
    static int N = sc.nextInt();
    static int count = 0;
public static void main(String[] args){
    
    for(int k=0; k<N; k++){
        if(wordCheck() == true){
            count++;
        }
    }
    System.out.println(count);
    sc.close();
    }

    public static boolean wordCheck(){
        boolean[] alpha = new boolean[26];
        int w1 = 0;
        String word = sc.next();
        for(int j=0; j<word.length(); j++){
            int w2 = word.charAt(j);

            if(w1 != w2){
                if(alpha[w2-97] == false){
                    alpha[w2-97] = true;
                    w1 = w2;
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
    
}

 

2. BufferedReader를 이용한 방법

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static int count = 0;
public static void main(String[] args)throws IOException{
    int N = Integer.parseInt(br.readLine());
    for(int k=0; k<N; k++){
        if(wordCheck() == true){
            count++;
        }
    }
    System.out.println(count);
    br.close();
    }

    public static boolean wordCheck()throws IOException{
        boolean[] alpha = new boolean[26];
        int w1 = 0;
        String word = br.readLine();
        for(int j=0; j<word.length(); j++){
            int w2 = word.charAt(j);
            if(w1 != w2){
                if(alpha[w2-97] == false){
                    alpha[w2-97] = true;
                    w1 = w2;
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
    
}

 

이번 문제가 어려웠기도 하고 몸져눕는 바람에 고난이 많았다.

처음에는 for문을 이용해서 풀려고 했는데 해결 되지도 않고 몸이 아프니 머리도 안돌아가서 결국 다른 분이 작성한 코드를 참고해 한 수 배우게 되었다.

 

자꾸 넓게 생각하지 못하는 게 너무 아쉽다... 알고리즘 공부 쉽지 않다ㅠ

 

출처 : https://st-lab.tistory.com/69

 

반응형