[알고리즘]/알고리즘

[알고리즘] 백준 6996번 : 애너그램 (브론즈1)

쿠릉쿠릉 쾅쾅 2022. 4. 23. 19:11
728x90

 

문제

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

 

풀이

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

class Main {

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

		StringTokenizer st = new StringTokenizer(br.readLine());
		
		int T = Integer.parseInt(st.nextToken());
		
		while(T --> 0) {
			
			Map<Character, Integer> map = new HashMap<>();
			st = new StringTokenizer(br.readLine());
			String first = st.nextToken();
			String second = st.nextToken();
			
			StringBuilder sb = new StringBuilder();
			sb.append(first)
				.append(" & ")
				.append(second)
				.append(" are ");
			
			int firstLength = first.length();
			int secondLength = second.length();
			
			if(firstLength!=secondLength) {
				sb.append("NOT anagrams.\n");
				bw.write(sb.toString());
				continue;
			}
			
			
			for(int i=0; i<firstLength; i++) {
				
				char firstKey = first.charAt(i);
				char secondKey = second.charAt(i);
				
				// 첫번째 단어의 문자 키의 벨류 값을 +1 올려준다.
				map.put(firstKey, map.containsKey(firstKey) ? map.get(firstKey)+1 : 1);
				// 두번쨰 단어의 문자 키의 벨류 값을 -1 내려준다.
				map.put(secondKey, map.containsKey(secondKey) ? map.get(secondKey)-1 : -1);
				
				// 첫 번째 단어의 문자 키의 벨류 값이 null 이거나 0일 경우 해당 키 값 삭제
				if(map.get(firstKey)==null || map.get(firstKey) == 0) map.remove(firstKey);
				// 두 번째 단어의 문자 키의 벨류 값이 null 이거나 0일 경우 해당 키 값 삭제
				if(map.get(secondKey)==null || map.get(secondKey) == 0) map.remove(secondKey);
			}
			
			if (map.size() == 0) {  // map 사이즈 개수가 0개일 경우 애너그램이다.
				sb.append("anagrams.\n");
				bw.write(sb.toString());
				continue;
			}
			
			sb.append("NOT anagrams.\n");
			bw.write(sb.toString());
			
		}
		
		bw.close();
		
	}
}

 

728x90