문제 풀이 (JAVA)

import java.io.*;
import java.util.*;
public class part4_2 {

	public static void main(String[] args) throws IOException {
		// 아나그램(해쉬)
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out));
		
		String a = br.readLine();
		String b = br.readLine();
		String answer =solution(a,b);
		
		bw.write(answer);
		bw.flush();
		bw.close();
	}
	private static String solution(String a , String b) {
		String result="YES"; // 기본 리턴 변수 Yes 
		HashMap<Character,Integer> map = new HashMap<>();
		HashMap<Character,Integer> map2 = new HashMap<>();
		for(int i=0; i<a.length(); i++) { // a 문자열  카운트
			map.put(a.charAt(i), map.getOrDefault(a.charAt(i), 0)+1);
		}
		for(int i=0; i<b.length(); i++) { // b 문자열 카운트
			map2.put(b.charAt(i), map2.getOrDefault(b.charAt(i), 0)+1);
		}
		for(Character key1 : map.keySet()) { //key값 for문 
			for(Character key2 : map2.keySet()) {
				// 단어 key가 같으나 숫자가 다르면 No 리턴
				if(key1 == key2 && map.get(key1) != map2.get(key2)) {
					result="NO";
				}
			}
		}	
		return result;
	}
}

해시 함수 정리

map.put(key,value) : map에 해당되는 key에 value를 INSERT or UPDATE 한다.

map.get(key) : key에 해당하는 value를 리턴한다.

map.containsKey(key) : map에 key가 존재하는지 확인하여 존재하면 true, 존재하지 않을 경우 false를 리턴한다.

map.getOrDefault(key,0) : map에 key가 존재하면 key의 value를 리턴하고, key가 존재하지 않으면 0을 리턴한다.

map.size() : map의 사이즈를 리턴한다.

map.remove(key) : key의 value를 출력하고, 해당 되는 key를  map에서 제거한다.

for (Character key : map.keySet()) : key를 순서대로 탐색한다.

 

 

주요 핵심 포인트

1. 두개의 해쉬맵을  선언 하여 key , value 값을 비교하여 푸는 기초적인 문제로 key를 비교하고 싶다면 for문의 keySet()을 잘 사용하여 풀도록 한다. 본 문제는 동일한 알파벳의 갯수가 같은지를 묻는 문제로 대소문자를 구분하여야 한다.

+ Recent posts