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.
给定两个 string, s 和 t,如果 s 和 t 用到的 chart 数量一样则回传 true
反之回传 false
,一样利用 hash-table 分别纪录两个 string 中 chart 出现的次数,最后将两个 hash-table 的内容作比较即可。
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
Coding
var isAnagram = function(s, t) { if (s.length !== t.length) return false const sObj = {}, tObj = {}; s.split('').forEach(s => { if (!sObj[s]) { sObj[s] = 1; } else { sObj[s]++; } }) t.split('').forEach(t => { if (!tObj[t]) { tObj[t] = 1; } else { tObj[t]++; } }) for (const key in sObj) { if (Object.hasOwnProperty.call(sObj, key)) { if (!tObj[key]) return false; if (sObj[key] !== tObj[key]) return false; } } return true;};
hash-table 的 get 为 O(1) 而 for-loop 两个 string 的遍历为 O(2n) -> O(n)
Time complexity: O(n)Space complexity: O(n)