0242-Valid-Anagram

Problem Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.

Solution

bool isAnagram(string s, string t) {
  if (s.size() != t.size()) {
    return false;
  }
  vector<int> letters(26);
  for (char c : s) {
    ++letters[c - 'a'];
  }
  for (char c : t) {
    if (--letters[c - 'a'] < 0) {
      return false;
    }
  }
  return true;
}