Last active
July 13, 2020 02:10
-
-
Save msinvent/83a8056bacbd384a055696b8e6482ec7 to your computer and use it in GitHub Desktop.
isAnagram function description
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool isAnagram(const std::string& str1, const std::string& str2) | |
{ | |
if(str1.size() != str2.size()){ | |
return false; | |
} | |
std::unordered_map<char,uint32_t> mapStr1; | |
std::unordered_map<char,uint32_t> mapStr2; | |
constexpr uint16_t maxSizeOfMap = 1<<(sizeof(char)*8); | |
mapStr1.reserve(maxSizeOfMap); | |
mapStr2.reserve(maxSizeOfMap); | |
// Loop through string and create frequency map of characters | |
// [O(n) average time complexity, O(1) space complexity, because the number of charactes types is fixed] | |
for(auto it: str1){ | |
mapStr1[it]++; | |
} | |
for(auto it: str2){ | |
mapStr2[it]++; | |
} | |
// Final search [O(n)] | |
return mapStr1 == mapStr2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment