ALGORITHM

[JAVA] 백준 2941번- 크로아티아 알파벳

연듀 2022. 8. 1. 10:20

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

 

2941번: 크로아티아 알파벳

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. 크로아티아 알파벳 변경 č c= ć c- dž dz= đ d- lj lj nj nj š s= ž z=

www.acmicpc.net

 

 

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

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

        String str = br.readLine();
        int cnt=str.length();

        for(int i=1; i<str.length(); i++){
            char ch = str.charAt(i);
            if(ch=='='){
                if(str.charAt(i-1)=='c' || str.charAt(i-1)=='s') cnt--;
                if(str.charAt(i-1)=='z'){
                    cnt--;
                    if(i>=2){
                        if(str.charAt(i-2)=='d') cnt--;
                    }
                }
            }
            if(ch=='-'){
                if(str.charAt(i-1)=='c' || str.charAt(i-1)=='d') cnt--;
            }
            if(ch=='j'){
                if(str.charAt(i-1)=='l' || str.charAt(i-1)=='n') cnt--;
            }
        }
        System.out.println(cnt);
    }
}

 

총 글자수에서 크로아티아 알파벳을 만날때마다 글자수를 하나씩 감소시키면 구하고자 하는 알파벳의 개수가 된다. 

=, -, j를 만날때 바로 직전의 알파벳을 확인하여 검사한다.

처음 제출했을 때 StringIndexOutOfBounds 런타임 에러가 떴는데, 이는 z=이전에 d인지를 검사할때 i>=2인지 체크를 안해줘서 였다.