w3resource
Java Programming Exercies

Java String Exercises: Find lexicographic rank of a given string

Java String: Exercise-50 with Solution

Write a Java program to find lexicographic rank of a given string.

Pictorial Presentation:

Java String Exercises: Find lexicographic rank of a given string

Sample Solution:

Java Code:

import java.util.*;
class Main {
 public static int makefactorial(int n) {
  return (n <= 2) ? n : n * makefactorial(n - 1);
 }
 public static int calcuLexicoRank(String str, int n) {
  int ctrOfRank = 1;
  for (int i = 0; i < n; i++) {
   int ctr = 0;
   for (int j = i + 1; j <= n; j++) {
    if (str.charAt(i) > str.charAt(j))
     ctr++;
   }
   ctrOfRank += ctr * makefactorial(n - i);
  }
  return ctrOfRank;
 }
 public static void main(String[] args) {
  String str = "BDCA";
  System.out.println("The Given String is: " + str);
  int n = str.length();
  System.out.print("The Lexicographic rank of the given string is: " + calcuLexicoRank(str, n - 1));
 }
}

Sample Output:

The Given String is: BDCA
The Lexicographic rank of the given string is: 12

N.B.: Total possible permutations of BDCA are(lexicographic order) :
ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA
1   2   3   4   5   6   7   8   9   10   11   12
The BDCA appear in 12 position of permutation (lexicographic order).

Flowchart:

Flowchart: Java String Exercises - Find lexicographic rank of a given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find first non-repeating character from a stream of characters.
Next: Write a Java program to count and print all the duplicates in the input string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming