I wrote an function to determine if string a is a permutation of string b. The definition is as follows:
bool isPermutation(std::string a, std::string b){
if(a.length() != b.length())
return false;
int a_sum, b_sum;
a_sum = b_sum = 0;
for(int i = 0; i < a.length(); ++i){
a_sum += a.at(i);
b_sum += b.at(i);
}
return a_sum == b_sum;
}
The issue with my approach is that if a = 600000 and b = 111111, the function returns true.
Is there any way I can keep my general approach to this problem (as opposed to sorting the strings then doing strcmp) and maintain correctness?
Aucun commentaire:
Enregistrer un commentaire