반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

배움과 기록의 장

[백준] 2941번: 크로아티아 알파벳 (Java) 본문

problem solving

[백준] 2941번: 크로아티아 알파벳 (Java)

chaeunii 2023. 3. 9. 22:42

✅ 문제

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

 

✅ 풀이

  • 먼저 목록에 나와있는 c=/c-/dz=/d-/lj/nj/s=/z=를 차례대로 갯수를 count 해주고, 제거해준다. 그 이후에 남은 알파벳들은 하나씩 count 해준다.
  • 예를 들어 c=의 경우,
    • c=의 갯수 count :
      {(기존 str길이) - (c=를 제거한 str길이)} / (c=의 길이) 를 해주면 된다.
       = (str.length() - str.replace("c=", "").length())/2
    • count 해준 c=를 제거 :
      str = str.replace("c=", " "

      * "" 이 아닌 " "으로 해줘야한다.
        그 이유는 예를 들어 "lc=j" 라는 문자열이 있을 때, 크로아티아 알파벳의 갯수는 l, c=, j 3개이다.
        우리의 로직대로 c=을 먼저 카운트하고 제거하면 "lj"가 남는다. 이때 l 과 j 는 각각 하나의 알파벳으로 취급되어야한다. 하지만 목록에 나와있는 알파벳 중 lj가 있기때문에, 우리의 로직대로라면 lj가 먼저 카운트 되어 하나의 알파벳으로 취급될 것이다. 따라서 c=을 제거할 때 공백을 넣어줌으로서 "l j"가 되어 이후에 lj로 카운트 되지 않고 l, j로 count 되게 해준 것이다.
  • 목록에 나와있는 알파벳들을 다 count 해주었다면, 임의로 추가해주었던 공백을 제거하고, 남은 알파벳들을 count 해주면 끝이다.
  • ++) 추가로, dz=와 z=는 카운트 및 제거 시에 순서가 중요하다. 문제에 dz= 는 d와 z=가 분리된 것으로 보지않는다고 적혀있다. 이 말은 즉슨, dz=가 있을 때 z=를 떼서 먼저 카운트 할 수 없다는 말이다. 따라서 dz=를 먼저 count 해주고, z=를 나중에 해줘야 올바르게 갯수를 셀 수 있다.
  •  

 

✅ 문제

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        int count = 0;

        //목록에 나와있는 알파벳 count하고 제거
        //c=
        if(str.contains("c=")){
            count += (str.length() - str.replace("c=", "").length())/2;
            str = str.replace("c=", " ");
        }
        //c-
        if(str.contains("c-")){
            count += (str.length() - str.replace("c-", "").length())/2;
            str = str.replace("c-", " ");
        }
        //dz=
        if(str.contains("dz=")){
            count += (str.length() - str.replace("dz=", "").length())/3;
            str = str.replace("dz=", " ");
        }
        //d-
        if(str.contains("d-")){
            count += (str.length() - str.replace("d-", "").length())/2;
            str = str.replace("d-", " ");
        }
        //lj
        if(str.contains("lj")){
            count += (str.length() - str.replace("lj", "").length())/2;
            str = str.replace("lj", " ");
        }
        //nj
        if(str.contains("nj")){
            count += (str.length() - str.replace("nj", "").length())/2;
            str = str.replace("nj", " ");
        }
        //s=
        if(str.contains("s=")){
            count += (str.length() - str.replace("s=", "").length())/2;
            str = str.replace("s=", " ");
        }
        //z=
        if(str.contains("z=")){
            count += (str.length() - str.replace("z=", "").length())/2;
            str = str.replace("z=", " ");
        }

        //남은 알파벳들 count
        count += str.replace(" ","").length();

        System.out.println(count);
    }
}

 

 

반응형