수쿵의 IT월드

DaleStudy | Leetcode Study 2주차 - Valid Anagram 본문

알고리즘

DaleStudy | Leetcode Study 2주차 - Valid Anagram

수쿵IT 2025. 7. 27. 17:17

Leetcode Study

문제

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

 

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^5
  • 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?

 

풀이

 

t가 s의 애너그램이라면, true를 리턴하고 아니라면 false를 리턴하면 되는 문제이다. 즉, s를 재배열해서 t를 만들 수 있다면 true를 리턴하면 된다. 이 문제는 객체에 각각 나온 수를 비교하는 방법과 자바스크립트 sort 함수를 이용해서 푸는 방법이 있는데, 가장 손쉽게 할 수 있는 방법은 sort함수를 이용하는 것이다. 

function isAnagram(s: string, t: string): boolean {
    return s.split('').sort().join() === t.split('').sort().join()
};

 

하지만 이렇게 풀면, 배열로 변경했다가 다시 문자열로 변경해야하는 작업이 있어 시간복잡도에서는 좋은 점수를 받지 못할 수 있다. 

 

객체를 이용해서 하는 방법은, 하나의 문자열을 객체로 변환한 후, 다른 문자열을 루프를 돌려 그 문자열이 존재하는지 안하는지를 객체에서 확인하면 된다.

function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;

  const objS: {[key: string]: number;} = {};

  for (const str of s) {
    objS[str] = (objS[str] ?? 0) + 1
  }

  for (const str of t) {
    if (!objS[str]) { return false; }
    objS[str]--;
  }

    return true;
}

 

 

 

Link: https://leetcode.com/problems/valid-anagram/description/