String permutations rank + data structure

前端 未结 3 1624
暖寄归人
暖寄归人 2021-02-08 01:05

The problem at hand is:

Given a string. Tell its rank among all its permutations sorted lexicographically.

The question can be at

3条回答
  •  后悔当初
    2021-02-08 01:31

    This is similar to the quickselect algorithm. In an unsorted array of integers, find the index of some particular array element. The partition element would be the given string.

    Edit:

    Actually it is similar to partition method done in QuickSort. The given string is the partition element.Once all permutations are generated, the complexity to find the rank for strings with length k would be O(nk). You can generate string permutations using recursion and store them in a linked list. You can pass this linked list to the partition method.

    Here's the java code to generate all String permutations:

     private static int generateStringPermutations(String name,int currIndex) {
    
            int sum = 0;
    
            for(int j=name.length()-1;j>=0;j--) {
                for(int i=j-1;((icurrIndex));i--) {
    
                    String swappedString = swapCharsInString(name,i,j);
                    list.add(swappedString);
                    //System.out.println(swappedString);
                    sum++;
                    sum = sum + generateStringPermutations(swappedString,i);
                }
            }
            return sum;
    
    
        }
    

    Edit:

    Generating all permutations is costly. If a string contains distinct characters, the rank can be determined without generating all permutations. Here's the link.

    This can be extended for cases where there are repeating characters.

    Instead of x * (n-1)! which is for distinct cases mentioned as in the link,

    For repeating characters it will be:

    if there is 1 character which is repeating twice,

    x* (n-1)!/2!

    Let's take an example. For string abca the combinations are:

    aabc,aacb,abac,abca,acab,acba,baac,baca,bcaa,caab,caba,cbaa (in sorted order)

    Total combinations = 4!/2! = 12

    if we want to find rank of 'bcaa' then we know all strings starting with 'a' are before which is 3! = 6.

    Note that because 'a' is the starting character, the remaining characters are a,b,c and there are no repetitions so it is 3!. We also know strings starting with 'ba' will be before which is 2! = 2 so it's rank is 9.

    Another example. If we want to find the rank of 'caba':

    All strings starting with a are before = 6. All strings starting with b are before = 3!/2! = 3 (Because once we choose b, we are left with a,a,c and because there are repetitions it is 3!/2!. All strings starting with caa will be before which is 1

    So the final rank is 11.

提交回复
热议问题