Valid Anagram Problem


Description

LeetCode Problem 242.

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    bool isAnagram(string s, string t) {
        map<int, int> ht;
        for (int i = 0; i < s.size(); i ++) {
            if (ht.find(s[i]) == ht.end()) 
                ht[s[i]] = 0;
            ht[s[i]] ++;
        }
        for (int i = 0; i < t.size(); i ++) {
            if (ht.find(t[i]) == ht.end())
                ht[t[i]] = 0;
            ht[t[i]] --;
        }
        bool anagram = true;
        for (map<int, int>::iterator mit = ht.begin(); 
            mit != ht.end(); mit ++) {
            if (mit->second != 0) {
                anagram = false;
                break;
            }
        }
        return anagram;
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...