Question:
1.3 Write a method to decide if two strings are permutation. i.e. “hello” is a permuataion of “oellh”.
If one string is a permutation of the other, they should has the same length and every character appear the same times in these two strings.
So the solution is to check the length and appear time of each character of these two strings.
We can use the same idea in question in 1.1 to solve this question. For example, use an array to store the appear time of all the characters in ASCII table.
Here is my solution, the time complexity was O(n) and space complexity is O(1).
bool permutation(string a, string b) { // if the length is different, can not be permutation if(a.size() != b.size()) return false; // use idea of Bucket-sort to count every ASCII character int bucket[256] = {}; // count the apprear time of every character in a for(size_t i=0; i<a.size(); i++) bucket[a[i]]++; // the appear time of character in b shold be the same with a for(size_t i=0; i<b.size(); i++) if(bucket[b[i]]-- == 0) return false; return true; }