1 minute read

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solution

Logic

  1. 문자열 s의 각 문자를 Key로하고, 해당 Key를 참조할 때마다 Key에 해당하는 Value를 1증가시키도록 문자열 s 전체를 참조한다.

  2. 문자열 t의 각 문자를 Key로하고, 해당 Key를 참조할 때마다 Key에 해당하는 Value를 1감소시키도록 문자열 t 전체를 참조한다.

  3. 문자열 s의 각 문자를 Key로 Value를 탐색하여 0이 아닌 Value가 있다면 false를 반환한다.

    Code

    class Solution {
     public boolean isAnagram(String s, String t) {
         if (s.length() != t.length()) return false;
         Map<Character, Integer> map = new HashMap<>();
         for (int i = 0; i < s.length(); i++) {
             map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
             map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) - 1);
         }
         for (int i = 0; i < s.length(); i++)
             if (map.get(s.charAt(i)) != 0) return false;
         return true;
     }
    }
    

    Time Complexity

    • 문자열 s의 길이를 n이라 가정할 때, 코드의 수행 시간을 지배하는 것은 for반복문의 n번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment