ZhuangER
9/30/2018 - 3:49 PM

[242. Valid Anagram] #tags: leetcode, leetcode/easy

[242. Valid Anagram] #tags: leetcode, leetcode/easy

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    if (s.length !== t.length) {
      return false;
    }
    const map = {};
    let result = true;
  
    for (let i = 0; i < s.length; ++i) {
      const sc = s[i];
      const tc = t[i];
      
      if (map[sc]) {
        map[sc] += 1;
      } else {
        map[sc] = 1;
      }
      
      if (map[tc]) {
        map[tc] -= 1;
      } else {
        map[tc] = -1;
      }
    }
  
    _.each(map, (value, key) => {
      if (value !== 0) {
        result = false;
      }
    })
  
    return result;
  
};
/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    return sortString(s) == sortString(t);
};

const sortString = (s) => {
  return s.split('').sort().join('');
}