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:
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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework