-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_anagram.cpp
49 lines (40 loc) · 1021 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
/*
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
*/
#include <algorithm> // for heap operations
#include <iostream>
using namespace std;
class Solution
{
public:
bool isAnagram(string sr, string te)
{
// if not same length then they can't be anagram by default
if (sr.length() != te.length())
{
return false;
}
// I take a hashtable and then increment from one string ( decrement from the other)
unordered_map<char, int> string1;
for (int i = 0; i < te.length(); i++)
{
string1[te[i]]++;
string1[sr[i]]--;
}
// if at any point they aren't even, then we have no anagram
for (auto c : string1)
{
if (c.second != 0)
{
return false;
}
}
return true;
}
};