DS & Algorithm

[백준/BOJ] 2941_크로아티아 알파벳(Java)

didue 2021. 12. 5. 23:16
반응형

입력

첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 -, =로만 이루어져 있다.

단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다.

출력

입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

예제 입력 1

입력 : ljes=njak
출력 : 6

예제 입력 2

입력 : ddz=z=
출력 : 3

예제 입력 3

입력 : nljj
출력 : 3

 

 


풀이

크로아티아 알파벳으로 표현되는 문자열을 1개의 문자로 인식하여 갯수를 세는 것이 문제풀이의 핵심이다.

그래서 이 문제 풀이에 크로아티아 알파벳을 1개로 셀 수 있도록 임의의 문자로 치환하여

갯수를 세는 문제 풀이 방법을 채택하였다.

문자열의 치환 방법에는 replace, replaceAll, replaceFirst 등이 있다.

 

풀이 코드

풀이 (1)

첫 문제 풀이에서는 크로아티아 문자를 공백("")으로 치환하여

처음 문자열과의 문자열 길이 차이를 구하여 크로아티아 알파벳의 갯수를 구한 뒤

일반 알파벳의 갯수를 구해 더하는 식으로 구현하였다.

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

public class Main {
    public static void main(String[] args) throws Exception{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        String[] croatiaAlpabet = new String[]{"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};

        int count = 0;

        for(String alpabet : croatiaAlpabet){
            int countOfString = countString(input, alpabet);
            if(countOfString > 0){
                count += countOfString/alpabet.length();
                input = input.replaceAll(alpabet," ");
            }
        }
        count += input.replaceAll(" ", "").length();

        System.out.println(count);
    }

    private static int countString(String input, String target){
        return input.length() - input.replaceAll(target, "").length();
    }
}

 

이 과정에서 크로아티아 알파벳을 공백이 아닌 임의의 한글자 알파벳으로 치환한 뒤

전체 문자열의 길이를 구할 수 있도록 코드를 간략화 할 수 있다는 것을 깨달았다.

 

 

여기에 replaceAll 메소드가 첫번째 argument로 regex(정규식)을 받음을 활용하여 숏코딩으로 표현할 수 있게 되었다!

 

풀이 (2)

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

public class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();

        System.out.println(input.replaceAll("c=|c-|dz=|d-|lj|nj|s=|z=","X").length());
    }
}
반응형