lundi 23 mars 2015

How to get the lexical rank of a string?


How to get the rank of a string which is the position that the word occupies in the lexical ordering of all permutations of the characters in that word?


For example:



rank("bac") = 2, bascules the lexical ordering is abc, acb, bac, bca, cab, cba(we use zero base index here)


I wrote a C++ solution works for strings that have distinct characters like the above example.



int getrank(string word) {
int size = word.size();
string temp = word;
sort(temp.begin(), temp.end());
int frac = 1;
for (int i = 2; i <= word.size() ;i++) {
frac *= i;
}
int res = 0;
for (int i = size; i > 1; i--) {
frac /= i;
int choosed = 0;
char check = word[size - i];
while (temp[choosed] != check)
choosed++;
res += choosed * frac;
temp.erase(choosed, 1);
}
return res;
}


However I am struggling to compute the rank of strings contain duplicate chars.


For example:



rank("abba") should equal to 2 because only aabb, abab are in front of it.


How to solve this problem?




Aucun commentaire:

Enregistrer un commentaire