Post

HashMap_Anagram

✅ Anagram: 알파벳 순서는 달라도 구성은 같은 string

두 string이 주어졌을 때, 알파벳 순서만 다르지 알파벳 구성이 같은지 확인하기
단, 대소문자는 서로 다른 문자로 취급합니다.
a와 A는 다른 문자입니다.

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
32
33
34
35
class Main {

    public String solution(String input1, String input2){
        String answer= "YES";
        HashMap<Character, Integer> map= new HashMap<>();
        for(char x: input1.toCharArray()){
            map.put(x, map.getOrDefault(x, 0)+1);
        }
        for(char x: input2.toCharArray()){
            if(!map.containsKey(x) || map.get(x)  == 0){
                answer = "NO";
            }else{
                map.put(x, map.get(x)-1);
            }
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        String input1= sc.next();
        String input2= sc.next();
        System.out.print(T.solution(input1, input2));
    }
}
//⭐️input:
// AbaAeCe
// baeeACA
//⭐️output:
//YES
//⭐️input:
// abaCC
// Caaab
//⭐️output:
//NO
  1. 먼저 첫 번째 string을 돌면서 HashMap을 만듭니다.
  2. 두 번째 string을 돌면서 HashMap에 그 key가 있는지 확인하고, 없으면? answer = “NO”
  3. 또는 있는지 확인했는데 value가 0이면? answer = “NO”
  4. key가 있고 value가 0이 아니면, key값에 대한 value를 1감소시킵니다.

🟢 두 개 string에 대해 두 개 HashMap 만들어서 HashMap이 일치하는지 확인하는 방법

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
class Main {

    public String solution(String input1, String input2){
        String answer= "YES";
        HashMap<Character, Integer> map1= new HashMap<>();
        HashMap<Character, Integer> map2= new HashMap<>();
        for(char x: input1.toCharArray()){
            map1.put(x, map1.getOrDefault(x, 0)+1);
        }
        for(char x: input2.toCharArray()){
            map2.put(x, map2.getOrDefault(x, 0)+1);
        }
        for(char x: map1.keySet()){
            if(map1.get(x) != map2.get(x)) answer= "NO";
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        String input1= sc.next();
        String input2= sc.next();
        System.out.print(T.solution(input1, input2));
    }
}
This post is licensed under CC BY 4.0 by the author.