Last active
July 13, 2020 02:42
-
-
Save msinvent/6f2fc38f5a11dbf2c6957f40efc2584d to your computer and use it in GitHub Desktop.
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; | |
} | |
constexpr uint16_t maxSizeOfMap = 1<<(sizeof(char)*8); | |
std::array<uint32_t,maxSizeOfMap> mapStr1; | |
std::array<uint32_t,maxSizeOfMap> mapStr2; | |
// Don't forget to perform initialization of variables in C++ | |
for(auto& it: mapStr1){ | |
it=0; | |
} | |
for(auto& it: mapStr2){ | |
it=0; | |
} | |
// 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[static_cast<uint8_t>(it)]++; | |
} | |
for(auto it: str2){ | |
mapStr2[static_cast<uint8_t>(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