Skip to content

Commit fb4a67b

Browse files
authored
Improved performance of valid anagram solution
1 parent 3d600b9 commit fb4a67b

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

ValidAnagram/solution.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ class Solution {
77
// Use hashmap to keep count of letters in both strings
88
unordered_map<char, int> letterCount;
99

10-
for (auto letter : s)
11-
letterCount[letter]++;
10+
if (s.length() != t.length())
11+
return false;
1212

13-
for (auto letter : t)
14-
letterCount[letter]--;
13+
for (int i=0; i<s.length(); i++)
14+
{
15+
letterCount[s.at(i)]++;
16+
letterCount[t.at(i)]--;
17+
}
1518

1619
// To be a valid anagram the letter counts in the hashmap should be all zeros if the count was the same in both strings
1720
for (const auto& [letter, count]: letterCount)

0 commit comments

Comments
 (0)