Skip to content

Instantly share code, notes, and snippets.

@pchong90

pchong90/1_3.cpp Secret

Created June 18, 2014 00:30
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 pchong90/c2badf9e895b8fbf7ee4 to your computer and use it in GitHub Desktop.
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.
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;
}
@larry-liu
Copy link

Your time complexity is O(M + N), instead of O(N)

@pchong90
Copy link
Author

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