Cosen95 / js_algorithm

🏂js数据结构与算法 系统学习
36 stars 10 forks source link

有效的字母异位词 #23

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago

leetcode: https://leetcode-cn.com/problems/valid-anagram/

Cosen95 commented 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结构来处理:

/**
 * @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
    }
};