코딩가딩가

[JAVA]BOJ 1919

Noooodle 2024. 1. 1. 14:27

문제

import java.util.*;

public class BOJ1919 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1, str2;
        int[] check_arr = new int[1000]; // str2의 중복 확인용 배열, 자동으로 0으로 초기화됨
        int cnt = 0;

        str1 = sc.nextLine();
        str2 = sc.nextLine();

        for(int i=0;i<str1.length();i++){
            for(int j=0;j<str2.length();j++){
                if((str1.charAt(i) == str2.charAt(j))&&(check_arr[j] == 0)){
                    cnt++;
                    check_arr[j] = 1;
                    break;
                }
            }
        }

        System.out.println((str1.length()+str2.length()) - (cnt*2));
    }
}

반복문을 사용해 글자 str1과 str2를 하나하나 비교해야겠다고 생각했다. check_arr은 문자를 중복해서 세지 않게하는 기능을 한다. 문자가 같고, 이미 체크하지 않았을때만 같은 문자가 있다고 세어준다.(if문 부분) 출력값은 애너그램을 만들기 위해 지워야 하는 문자의 수이므로, 'str1의 길이+str2의 길이'에서 '애너그램이 되는 문자의 수*2'를 빼주면 정확하게 나온다.

 

그림으로 보자면 이런식으로.. 

str1의 문자와 str2의 문자가 같은 순간이 오면, 중복되지 않도록 check_arr을 1로 바꿔주고 같은 문자가 있다고 cnt를 1개 증가시킨 후 break;한다. break를 해야 str2의 마지막에 있는 b를 체크하지 않을 것이다.

str1의 두번째 b를 확인할때, check_arr을 1로 바꿔줬기 때문에 중복되는 값 없이 제대로 애너그램인지 확인할 수 있다.

 

 


또 다른 방법

애너그램은 같은 문자가 같은 개수끼리 있는 것이므로, str1의 문자 구성과 str2의 문자구성을 비교하면 된다. str1에 관해 문자구성을 만든 배열1, str2에 관해 문자구성을 만든 배열2를 생성하고 차이를 구하면 된다.

import java.util.*;

public class BOJ1919 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1, str2;

        str1 = sc.nextLine();
        str2 = sc.nextLine();

        int ans = 0;
        int[] count1 = new int[26]; // 알파벳은 26글자, 입력값은 소문자로만 이뤄져있음
        int[] count2 = new int[26];

        // String의 문자 구성을 배열에 저장, 인덱스번호를 맞추기 위해 -'a'가 필요
        for(int i=0;i<str1.length();i++)
            count1[str1.charAt(i)-'a']++;
        for(int i=0;i<str2.length();i++)
            count2[str2.charAt(i)-'a']++;
        for(int i=0;i<26;i++){
            if(count1[i]>count2[i])
                ans += count1[i] - count2[i];
            else if(count2[i]>count1[i])
                ans += count2[i] - count1[i];
        }
        System.out.println(ans);
    }
}

위 코드를 좀 더 깔끔하게 정리할 수 있다. 알파벳 구성 배열을 만드는 함수를 만들고 마지막에 차이를 구할때도 절대값을 이용하는 방법이다.

import java.util.*;

public class BOJ1919 {
    public static int[] getAlphabetCount(String str){
        int[] count = new int[26];

        for(int i=0;i<str.length();i++)
            count[str.charAt(i)-'a']++;

        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1, str2;

        str1 = sc.nextLine();
        str2 = sc.nextLine();

        int ans = 0;
        int[] count1 = getAlphabetCount(str1);
        int[] count2 = getAlphabetCount(str2);

        for(int i=0;i<26;i++)
            ans += Math.abs(count1[i] - count2[i]); // 절대값을 취해서 계산함

        System.out.println(ans);
    }
}

'코딩가딩가' 카테고리의 다른 글

[JAVA]BOJ 13223  (0) 2024.01.10
[JAVA]BOJ 1543  (0) 2024.01.04
[JAVA]BOJ 1157  (0) 2024.01.02
[JAVA]BOJ 2744  (1) 2023.12.31
[JAVA]String  (0) 2023.12.28