字符串Java的词典排名

时间:2014-08-07 17:04:19

标签: java permutation ranking lexicographic

我正在尝试编写一个包含“'字”的程序。来自用户并在其所有排列中打印出其词典排名。我有获得排名和计算阶乘的函数(由于复杂性原因迭代)但我需要一个主方法来测试程序并使其可运行。这就是我到目前为止所拥有的:

编辑:我正在尝试将执行上述操作的this C program转换为Java。我遇到了麻烦,主要是增加和更新Count函数得到错误:
    The type of expression must be an array type but i resolved to int/String.

package ranking;

public class Ranking {

public static void increaseCount (int count, String str) {
    int i;
    for (i=0; str[i]; i++)
        count[str[i]]++;

    for (i=1; i < 256; i++)
        count[i] += count[i-1];
}

public static void updateCount (int count, String ch){
    int i;
    for (i=ch; i < 256; i++)
        count[i]--;
}

public static int findRank (String str) {
    int length = str.length();
    int mul = fact(length);
    int rank = 1, i;
    int count[256] = {0};

    increaseCount(count, str);

    for (i=0; i < length; i++) {
        mul/= length - i;

        rank += count [ str[i] - 1] * mul;

        updateCount(count, str[i];)
    }
    return rank;
}

public static int factorial (int n){
    int fact = 1;
    if (n ==0 || n==1) {
        return 1;
    }
    else {
        for (int i=1; i<=n; i++){
            fact *= i;
        }
    }
    return fact;
}

public static void main (String[] args){
    String str = "string";
    System.out.print(findRank(str));
}

}

1 个答案:

答案 0 :(得分:0)

试试一下循环:

public static void main(final String[] args) {
    final Scanner scan = new Scanner(System.in);
    System.out.println("Enter a string: ");
    String inputChars;
    while (!(inputChars = scan.next()).equals("exit")) {
        System.out.println(inputChars);
    }
    scan.close();
}

测试。的工作原理。