242. Valid Anagram
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 * 10^4
s
andt
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
的字母异位词。
注意:若 s
和 t
中每个字符出现的次数都相同,则称 s
和 t
互为字母异位词。
解题思路
可以使用哈希表,扫描字符串 s
,把 s
中的每个字符出现的次数存在哈希表中,再扫字符串 t
,每出现一个字母就把哈希表中对应的字符减一,异位词中字符出现的次数肯定都是一样的,最终判断表中是否全部为 0
即可,有非 0
的数就输出 false
。
代码
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
let map = new Map();
for (let i of s) {
let val = map.get(i) || 0;
map.set(i, val + 1);
}
for (let j of t) {
let val = map.get(j) || 0;
map.set(j, val - 1);
}
return [...map.values()].filter((i) => i != 0).length === 0;
};
相关题目
相关题目
- [49. 字母异位词分组](https://leetcode.com/problems/group-anagrams)
- [🔒 Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation)
- [438. 找到字符串中所有字母异位词](https://leetcode.com/problems/find-all-anagrams-in-a-string)
- [2273. 移除字母异位词后的结果数组](https://leetcode.com/problems/find-resultant-array-after-removing-anagrams)