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

Find Duplicate Subtrees Problem

LeetCode 652. Given the rootof a binary tree, return all...

Delete And Earn Problem

LeetCode 740. You are given an integer array nums. You...

Degree Of An Array Problem

LeetCode 697. Given a non-empty array of non-negative integers nums,...

Custom Sort String Problem

LeetCode 791. You are given two strings order and s....

Basic Calculator IV Problem

LeetCode 770. Given an expression such as expression = “e...

Sort Characters By Frequency Problem

LeetCode 451. Given a string s, sort it in decreasing...