-
-
Save pchong90/c2badf9e895b8fbf7ee4 to your computer and use it in GitHub Desktop.
CarrerCup 1.3 Given two strings, write a method to decide if one is a permutation of the other.
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 permute_str(const string &str1, const string &str2){ | |
if (str1.empty() || str2.empty()){ | |
return false; | |
} | |
if (str1.length() != str2.length()){ | |
return false; | |
} | |
int ascii[256] = {0}; | |
for (size_t i = 0; i < str1.length(); ++i){ | |
++ascii[int(str1[i])]; | |
--ascii[int(str2[i])]; | |
} | |
for (size_t i = 0; i < 256; ++i){ | |
if (ascii[i] != 0) | |
return false; | |
} | |
return true; | |
} |
The cost of first loop is N=length of string
and the cost of second loop is at most 256. So the time complexity is O(N+256) = O(N)
. I read your code and I think we use the same algorithm.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your time complexity is O(M + N), instead of O(N)