Skip to content

Instantly share code, notes, and snippets.

@msinvent
Last active July 13, 2020 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msinvent/6f2fc38f5a11dbf2c6957f40efc2584d to your computer and use it in GitHub Desktop.
Save msinvent/6f2fc38f5a11dbf2c6957f40efc2584d to your computer and use it in GitHub Desktop.
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