애너그램은 단어 A가 주어졌을 때 문장을 이루는 알파벳을 바꿔서 다른 단어 B를 만들 수 있으면 A와 B를 애너그램이라고 한다.

예를 들어 A = abc라고 하면 B = abc, acb, bac, bca, cab, cba가 될 수 있다.

 

문제의 요점은 A와 B는 모두 같은 길이로 되어있는 구성이 같은 알파벳의 나열이라는 것이다. 그렇다면 순서와 상관없이 알파벳의 갯수만 체크하면 간단히 풀릴 것이다.

 

알파벳의 총 개수는 52개이며 아스키코드값에 의해  A = 65, B = 65, ... ,Z = 90, a = 97, b = 98, ..., z = 122가 된다.

해당 숫자들을 0~52까지 매핑 시킨 후, 갯수를 체크하면 된다.

다음은 전체 소스 코드이다.

 

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

        int n = Integer.parseInt(br.readLine());

        while (n-- > 0) {
            int[] ana = new int[52];
            StringTokenizer st = new StringTokenizer(br.readLine());
            String s1 = st.nextToken();
            String s2 = st.nextToken();
            boolean result = true;

            if (s1.length() != s2.length()) {
                bw.write(s1 + " & " + s2 + " are NOT anagrams.\n");
                continue;
            }

            for (int i = 0; i < s1.length(); i++) {
                int c = s1.charAt(i);
                if (c >= 65 && c <= 90) {
                    ana[c - 65]++;
                } else if (c >= 97 && c <= 122) {
                    ana[c - 71]++;
                }
            }

            for (int i = 0; i < s2.length(); i++) {
                int c = s2.charAt(i);
                if (c >= 65 && c <= 90) {
                    ana[c - 65]--;
                } else if (c >= 97 && c <= 122) {
                    ana[c - 71]--;
                }
            }

            for (int i = 0; i < 52; i++) {
                if (ana[i] != 0) {
                    result = false;
                    break;
                }
            }
            if (result == true) {
                bw.write(s1 + " & " + s2 + " are anagrams.\n");
            } else {
                bw.write(s1 + " & " + s2 + " are NOT anagrams.\n");
            }
        }
        bw.flush();
        bw.close();
    }
}

'알고리즘 풀이' 카테고리의 다른 글

[백준] 2579번 계단 오르기  (0) 2020.04.01
[HackerRank] Max Array Sum  (0) 2020.04.01
[HackerRank] Abbreviation  (0) 2020.04.01
[백준] 2960번 에라토스테네스의 체  (0) 2020.03.27

+ Recent posts