Previous Page
cover
Leetcode
TypeScript
Easy
Author: Edison Chue 2022-01-28 5 mins read

242 - Valid Anagram

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 * 104
  • 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?

中文題解

給予兩字串 s 與  t,若 t 爲 s 的 Anagram(t 包含 s 所有的字元而且各字元的出現數量一樣),返回 True,否則 False。

思路

爲兩字串建立各自的 Hashmap,迭代字串並記錄各字串字元出現的次數,比對兩 Hashmap,若出現對方沒有的字元或是字元出現的數量不一樣,回傳 False。

function isAnagram(s: string, t: string): boolean {
    // 兩字串長度不一一定不會是Anagram
    if (s.length !== t.length) return false
    
    // 建立各自的 Hashmap
    const mapS = {}, mapT = {}
    
    for (let i = 0; i < s.length; i++) {
        mapS[s[i]] = s[i] in mapS ? mapS[s[i]] + 1 : 0 
        mapT[t[i]] = t[i] in mapT ? mapT[t[i]] + 1 : 0 
    }
    
    // 比對兩Hashmap
    for (let key in mapS) {
        if (mapS[key] !== mapT[key]) return false
    }
    
    return true
};