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;
}
};