Skip to content

Instantly share code, notes, and snippets.

@AmnesiacSloth
Created September 13, 2024 01:40
Show Gist options
  • Save AmnesiacSloth/70ad70f5681604f96ab3d010e1780c7c to your computer and use it in GitHub Desktop.
Save AmnesiacSloth/70ad70f5681604f96ab3d010e1780c7c to your computer and use it in GitHub Desktop.
class betterSolution {
public:
bool isAnagram(string s, string t) {
unordered_map <char,int> trackMap;
if (t.size() != s.size()) {
return false; // If lengths are not equal, impossible to be anagram
}
// for s, increment counts, for t decrement
/*
for (u_int i=0 ; i < s.size(); i++) causes a slower runtime, why?
- Maybe conversion from u_int to int for operator[] location?
*/
for (int i = 0; i < s.size(); i++) {
trackMap[s[i]]++;
trackMap[t[i]]--;
}
for (auto kvPairs: trackMap) {
if (kvPairs.second != 0) {
return false; // characters did not match up exactly.
}
}
return true; // All counts in hashmap are zero, meaning same letters and counts in both s and t
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char,int> s_map,t_map;
for (int i = 0; i < s.size(); i++) {
if (s_map.count(s[i])) {
s_map.at(s[i])++; // increment number of times weve seen this character
}
else {// add first instance of char to map
s_map.insert({s[i],1});
}
}
for (int i = 0; i < t.size(); i++) {
if (t_map.count(t[i])) {
t_map.at(t[i])++; // increment number of times weve seen this character
}
else {// add first instance of char to map
t_map.insert({t[i],1});
}
}
return t_map == s_map;
}
};

Valid Anagram 📗

Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment