highlight:
1.permutation comparison is case sensitive or whitespace is significant
2.two strings with different length cannot be permutations of each other
解法一:sort
bool isPermutation(string str1, string str2){
int len = str1.size();
if(str2.size()!=len){
return false;
}
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
for(int i=0;i<len;i++){
if(str1[i]!=str2[i]){
return false;
}
}
return true;
}
解法二:count each character
bool isPermutation(string str1, string str2){
int len = str1.size();
if(len!=str2.size()){
return false;
}
int counts[128] = {};
for(char c: str1){
counts[c]++;
}
for(char c: str2){
counts[c]--;
if(counts[c]<0){
return false;
}
}
return true;
}