leetcode: 242. valid anagram

题目描述

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

Example 1:

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

Example 2:

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

使用unordered_map实现。

代码实现

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
26
27
28
class  {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> mapDic;
for (auto i: s) {
if (mapDic.find(i) == mapDic.end()) {
mapDic[i] = 1;
} else {
mapDic[i] += 1;
}
}

for (auto i: t) {
if (mapDic.find(i) == mapDic.end()) {
return false;
} else {
if (--mapDic[i] == 0)
mapDic.erase(mapDic.find(i));
}
}

if (mapDic.empty() == true) {
return true;
}

return false;
}
};