-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode-242.js
48 lines (39 loc) · 1.21 KB
/
Leetcode-242.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 242. Valid Anagram
* https://leetcode.com/problems/valid-anagram/
* @param {string} s
* @param {string} t
* @return {boolean}
*/
// 1. 暴力法:sort一下,看两数组是否相等 O(nlogn)
// const isAnagram = (s, t) => {
// return s.split('').sort().join('') == s.split('').sort().join('')
// }
// 2. HashTable O(n)
// 遍历数组一,用哈希表记录每个字符出现的次数,再遍历数组二,减掉每个字符出现的次数及清除key,最后如果空对象,即是Anagram
const isAnagram = (s, t) => {
let table = {}
for (let i = 0; i < s.length; i++) {
table[s[i]] ? table[s[i]] += 1 : table[s[i]] = 1
}
for (let i = 0; i < t.length; i++) {
if (table[t[i]]) {
table[t[i]] -= 1
if (table[t[i]] == 0) delete(table[t[i]])
} else return false
}
return Object.keys(table) == 0
}
/**
* Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
*/