-
Notifications
You must be signed in to change notification settings - Fork 17
/
LexicographicRankProblem.java
42 lines (41 loc) · 1.06 KB
/
LexicographicRankProblem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package SummerTrainingGFG.Strings;
/**
* @author Vishal Singh
* Reference - Geeks for geeks
*/
public class LexicographicRankProblem {
static int fact(int i){
if (i == 0 || i == 1){
return 1;
}
int fact = 1;
for (int j = 2; j <= i; j++) {
fact = fact*j;
}
return fact;
}
static int lexRank(String str){
int n = str.length();
int mul = fact(n);
int rank = 1;
int[] count = new int[256];
for (int i = 0; i < n; i++) {
count[str.charAt(i)]++;
}
for (int i = 1; i < 256; i++) {
count[i] += count[i-1];
}
for (int i = 0; i < n; i++) {
mul = mul/(n-i);
rank += (count[str.charAt(i)-1]*mul);
for (int j = str.charAt(i); j < 256; j++) {
count[j]--;
}
}
return rank;
}
public static void main(String[] args) {
String str = "string";
System.out.println("Lex Rank of "+str+" is : "+lexRank(str));
}
}