给定两个字符串 s
和 t
,编写一个函数来判断它们是不是一组变位词(字母异位词)。
注意:若 *s*
和 *t*
中每个字符出现的次数都相同且字符顺序不完全相同,则称 *s*
和 *t*
互为变位词(字母异位词)。
示例 1:
输入:s = "anagram", t = "nagaram"
输出:true
示例 2:
输入:s = "rat", t = "car"
输出:false
示例 3:
输入:s = "a", t = "a"
输出:false
提示:
1 <= s.length, t.length <= 5 * 104
s
和 t
仅包含小写字母分析:
如果两字符串相等
或两字符串长度不等
,直接返回false
。
定义一个数组counts
,长度为26,默认填充0,用来计数字母个数。
遍历字符串s
,计数++。
遍历字符串t
,如果当前字符对应的counts[index]为0,说明还没有进行减操作就为0了,说明肯定不是异位词。接着就是对应字符进行–操作。
看例子s = "anagram", t = "nagaram"
遍历s进行计数,得到counts=[3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
遍历t进行减减,没有遇到counts[index] === 0的情况。
遍历完counts元素均为0.默认返回true。
var isAnagram = function(s, t) {
if (s.length !== t.length || s === t) return false;
let counts = new Array(26).fill(0);
for (let ch of s) {
counts[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
for (let ch of t) {
let index = ch.charCodeAt(0) - 'a'.charCodeAt(0);
if (counts[index] === 0) {
return false;
}
counts[index]--;
}
return true;
};
var isAnagram = function(s, t) {
if (s.length !== t.length || s === t) {
return false;
}
let counts = new Map();
for (let ch of s) {
counts.set(ch, (counts.get(ch) || 0) + 1);
}
for (let ch of t) {
if ((counts.get(ch) || 0) === 0) {
return false;
}
counts.set(ch, counts.get(ch) - 1);
}
return true;
}