-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid_anagram.cpp
49 lines (43 loc) · 997 Bytes
/
valid_anagram.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 242. Valid Anagram: https://leetcode.com/problems/valid-anagram
// Author: [email protected]
#include <assert.h>
#include <stdio.h>
#include <string>
#include <vector>
class Solution
{
public:
bool isAnagram(const std::string& s, const std::string& t)
{
const int size = 'z' - 'a' + 1;
std::vector<int> counts(size, 0);
for (const auto chr: s)
{
counts[chr - 'a'] += 1;
}
for (const auto chr: t)
{
if (counts[chr - 'a'] == 0)
{
return false;
}
counts[chr - 'a'] -= 1;
}
for (const auto val: counts)
{
if (val > 0)
{
return false;
}
}
return true;
}
};
int main(int argc, char* argv[])
{
std::string s = "anagram";
std::string t = "nagaram";
bool is_anagram = Solution().isAnagram(s, t);
assert(is_anagram == true);
return 0;
}