Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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

Visualize Java code execution (Python Tutor):


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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe