我试图在可能的排列列表中找到给定字符串的等级。我试图提出一个解决方案,试图找到所有可能的排列,为它们分配一个等级,然后显示它。
但是当字符串的长度不断增加时,这会大大降低性能。所以想知道是否有人能想到一个有效的解决方案来解决这个问题..
function permute(str) {
// Sort the string
var arr = [];
for (var i = 0; i < str.length; i++) arr.push(str[i]);
var sortedString = arr.sort().join(''),
// Length of the string
length = str.length,
used = [];
// Create a boolean array for length of the string
while (length--) used.push(false);
// String buffer that holds the current string
var out = '';
// Call the function
doPermute(sortedString, str, out, used, str.length, 0);
}
var count = 0;
function doPermute(inp, givenString, out, used, length, level) {
// Only if length of the string equal to current level print it
// That is permutation length is eqaul to string length
if (level == length) {
count++;
//console.log('Perm :: ' + out + ' -- ' + count);
if (out === givenString) {
var pp = 'Rank of :: ' + out + ' -- ' + count;
$('div').append('<p>' + pp + '</p>');
}
return;
}
for (var i = 0; i < length; ++i) {
// If variable used continue
if (used[i]) continue;
// Append the current char in loop
out += inp[i];
// set variable to true
used[i] = true;
// Call the function again
doPermute(inp, givenString, out, used, length, level + 1);
// Set it to false as the variable can be reused
used[i] = false;
// remove the last character of the buffer
out = out.slice(0, out.length - 1)
}
}
permute('dbcarf')