Skip to content

Commit 30a4b2b

Browse files
committed
Refine valid-anagram solution
1 parent b82d35f commit 30a4b2b

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

valid-anagram/OstenHun.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,50 @@
55
An anagram is a word or phrase formed by rearranging
66
the letters of a different word or phrase,
77
using all the original letters exactly once.
8+
9+
Input: s = "anagram", t = "nagaram"
10+
Output: true
811
*/
912

1013
#include <string>
14+
#include <unordered_map>
1115
using namespace std;
1216

17+
#pragma region FirstIdea_TwoArrays
18+
namespace first_idea {
19+
20+
class Solution {
21+
public:
22+
bool isAnagram(const string& s, const string& t) {
23+
int freq_s[26] = {};
24+
int freq_t[26] = {};
25+
26+
if (s.length() != t.length()) {
27+
return false;
28+
}
29+
30+
for (size_t i = 0; i < s.length(); i++) {
31+
freq_s[s[i] - 'a']++;
32+
}
33+
34+
for (size_t i = 0; i < t.length(); i++) {
35+
freq_t[t[i] - 'a']++;
36+
}
37+
38+
for (int i = 0; i < 26; i++) {
39+
if (freq_s[i] != freq_t[i]) {
40+
return false;
41+
}
42+
}
43+
44+
return true;
45+
}
46+
};
47+
48+
} // namespace first_idea
49+
#pragma endregion
50+
51+
#pragma region FinalSolution_OneArray
1352
class Solution {
1453
public:
1554
bool isAnagram(const string& s, const string& t) {
@@ -33,3 +72,37 @@ class Solution {
3372
return true;
3473
}
3574
};
75+
#pragma endregion
76+
77+
#pragma region Alternative_UnorderedMap
78+
namespace unordered_map_idea {
79+
80+
class Solution {
81+
public:
82+
bool isAnagram(const string& s, const string& t) {
83+
if (s.length() != t.length()) {
84+
return false;
85+
}
86+
87+
unordered_map<char, int> freq;
88+
89+
for (char ch : s) {
90+
freq[ch]++;
91+
}
92+
93+
for (char ch : t) {
94+
freq[ch]--;
95+
}
96+
97+
for (const auto& [ch, count] : freq) {
98+
if (count != 0) {
99+
return false;
100+
}
101+
}
102+
103+
return true;
104+
}
105+
};
106+
107+
} // namespace unordered_map_idea
108+
#pragma endregion

0 commit comments

Comments
 (0)