Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 85032df

Browse files
committed
feat: add is anagram implementation
1 parent 2a27607 commit 85032df

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎js/is_anagram.js‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022年05月21日 23:30:44
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022年05月21日 23:35:00
6+
*/
7+
8+
/**
9+
* 来源:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn96us/
10+
*
11+
* 242. 有效的字母异位词
12+
*
13+
* 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
14+
* 注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
15+
*
16+
* 示例 1:
17+
* 输入: s = "anagram", t = "nagaram"
18+
* 输出: true
19+
*
20+
* 示例 2:
21+
* 输入: s = "rat", t = "car"
22+
* 输出: false
23+
*
24+
* 提示:
25+
* 1 <= s.length, t.length <= 5 * 10^4
26+
* s 和 t 仅包含小写字母
27+
* 进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
28+
*
29+
*/
30+
31+
const isAnagram = (s, t) => {
32+
const calcStrCount = (s) => {
33+
let cacheMap = {};
34+
35+
for (let i = 0, len = s.length; i < len; i++) {
36+
const value = s[i];
37+
38+
// 计算字符串每个字符出现的次数
39+
cacheMap[value] =
40+
typeof cacheMap[value] !== "undefined"
41+
? cacheMap[value] + 1
42+
: 1;
43+
}
44+
45+
return cacheMap;
46+
};
47+
48+
const sMap = calcStrCount(s);
49+
const tMap = calcStrCount(t);
50+
51+
const getResult = (map1, map2) => {
52+
if (Object.values(map1).length < Object.values(map2).length) {
53+
return getResult(map2, map1);
54+
}
55+
56+
for (const item in map1) {
57+
if (map1[item] !== map2[item]) {
58+
return false;
59+
}
60+
}
61+
62+
return true;
63+
};
64+
65+
return getResult(sMap, tMap);
66+
};
67+
68+
console.log(isAnagram("anagram", "nagaram"));
69+
console.log(isAnagram("rat", "car"));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /