242. Valid Anagram

Difficulty:
Related Topics:
Similar Questions:

Problem

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

Solution 1

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
  var lenA = s.length;
  var lenB = t.length;
  var map = {};

  if (lenA !== lenB) return false;

  for (var i = 0; i < lenA; i++) {
    if (!map[s[i]]) map[s[i]] = 0;
    map[s[i]]++;
  }

  for (var j = 0; j < lenB; j++) {
    if (!map[t[j]]) return false;
    map[t[j]]--;
  }

  return true;
};

Explain:

nope.

Complexity:

Solution 2

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
  var lenA = s.length;
  var lenB = t.length;
  var map = Array(26);
  var index = 0;
  var base = 'a'.charCodeAt(0);

  if (lenA !== lenB) return false;

  for (var i = 0; i < lenA; i++) {
    index = s[i].charCodeAt(0) - base;
    if (!map[index]) map[index] = 0;
    map[index]++;
  }

  for (var j = 0; j < lenB; j++) {
    index = t[j].charCodeAt(0) - base;
    if (!map[index]) return false;
    map[index]--;
  }

  return true;
};

Explain:

nope.

Complexity: