Open Cosen95 opened 4 years ago
首先能想到的一种是先转成数组,再排序,然后转换回字符串,比较两个字符串是否相同即可。
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
return s.split('').sort().join('') === t.split('').sort().join('')
};
还有一种方法是通过map
结构来处理:
Map
的 map
对象;s
, 将各字母出现的次数叠加存储进 map
中;t
, 在 map
中减少相应字母出现的个数, 并增加 map
中未收录的字母;map
的 size
不为 0, 则 s
与 t
不是字母异位词; 否则是字母异位词;/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
const map = new Map();
for (let i=0; i< s.length; i++) {
const getMap = map.get(s[i])
if(!getMap) {
map.set(s[i], 1)
} else {
map.set(s[i], getMap+1)
}
}
for (let i=0; i< t.length; i++) {
const getMap = map.get(t[i]);
if(getMap === 1) {
map.delete(t[i])
} else if(getMap) {
map.set(t[i], getMap-1)
} else {
map.set(t[i], 1)
}
}
if (map.size) {
return false
} else {
return true
}
};
leetcode: https://leetcode-cn.com/problems/valid-anagram/