[LeetCode] Valid Anagram

아르당·2025년 11월 10일

LeetCode

목록 보기
60/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 문자열 s와 t가 주어졌을 때, t가 s의 아나그램이면 true를 반환하고, 그렇지 않다면 false를 반환해라.

Example

#1
Input: s = "anagram", t = "nagaram"
Output: true

#2
Input: s = "rat", t = "car"
Output: false

Constraints

  • 1 <= s.length, t.length <= 5 * 10^4
  • s와 t는 영어의 소문자로만 구성된다.

Solved

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;

        Map<Character, Integer> counter = new HashMap<>();

        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            counter.put(ch, counter.getOrDefault(ch, 0) + 1);
        }

        for(int i = 0; i < t.length(); i++){
            char ch = t.charAt(i);

            if(!counter.containsKey(ch) || counter.get(ch) == 0){
                return false;
            }

            counter.put(ch, counter.get(ch) - 1);
        }

        return true;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글