본문 바로가기
Beakjoon&프로그래머스/Java

[LeetCode/Java] Valid Anagram

by 현장 2025. 12. 31.

-Code

import java.util.*;

class Solution {
    public boolean isAnagram(String s, String t) {
        // 길이가 다르면 실패
        if (s.length() != t.length()) {
            return false;
        }
        Map<Character, Integer> wordCnt = new HashMap<>();
        // 문자의 갯수를 셋팅
        for (char ch : s.toCharArray()) {
            wordCnt.put(ch, wordCnt.getOrDefault(ch, 0) + 1);
        }
        // 문자열 갯수와 비교
        for(char ch : t.toCharArray()) {
            if (!wordCnt.containsKey(ch) || wordCnt.get(ch) == 0) {
                return false;
            }
            wordCnt.put(ch, wordCnt.get(ch) - 1);
        }
       
        return true;
    }
}