-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0242-valid-anagram.js
More file actions
51 lines (40 loc) · 1.27 KB
/
Copy path0242-valid-anagram.js
File metadata and controls
51 lines (40 loc) · 1.27 KB
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
49
50
51
//Blog: https://www.allenliservice.online/leetcode-js-242-valid-anagram/
// <strong>Solution:</strong>
// 1. 先判斷 s 和 t 的長度是否不相同,並回傳 false。
// 2. 將 s 和 t 字串切割,並進行字母排序,再將字母組合。
// 3. 判斷 s 和 t 是否相同,並回傳true,反之回傳 false。
// <strong>Code 1: BigO(n log n)</strong>
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;
let sortS = s.split("").sort().join(""),
sortT = t.split("").sort().join("");
return sortS === sortT;
};
/* <strong>FlowChart:</strong>
<strong>Example 1</strong>
Input: s = "anagram", t = "nagaram"
s = "aaagmnr"
t = "aaagmnr"
return true */
// <strong>Code 2: BigO(n log n)</strong>
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;
if (s.split("").sort().join("") === t.split("").sort().join("")) {
return true;
} else {
return false;
}
};
// <strong>Code 3: BigO(2n)</strong>
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;
const hashTable = {};
for (let i = 0; i < s.length; i++) {
hashTable[s[i]] = (hashTable[s[i]] || 0) + 1;
}
for (let j = 0; j < t.length; j++) {
if (!hashTable[t[j]]) return false;
hashTable[t[j]]--;
}
return true;
};