算法设计:字典序问题

算法设计:字典序问题_第1张图片算法设计:字典序问题_第2张图片

代码实现:

@Test
public void fn1_2_1() {
int n = new Scanner(System.in).nextInt();
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < n; i++) {
list.add(sc.nextLine());
}
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
int len = str.length();
byte[] bs = str.getBytes();
int[] is = new int[len];
for (int m = 0; m < len; m++) {
is[m] = (int) bs[m] - 96;
}
long num1 = 0l;
for (int p = 1; p < len; p++) {
num1 += getAll(p);
}
long num2 = 0l;
num2 = getCode(is, num2, 1);
if (len == 1) {
num2++;
}
long result = num1 + num2;
System.out.println(result);
}
}
private long getCode(int[] is, long rel, int start) {
int len = is.length;
if (len > 0) {
int first = is[0];
int[] temp = new int[len - 1];
for (int i = 0; i < len - 1; i++) {
temp[i] = is[i + 1];
}
for (int i = 1; i < first; i++) {
if (i >= start) {
rel += getByFirst(i, len);
}
}
start = first;
return getCode(temp, rel, start);
} else {
return rel;
}
}
// 长度为k的升序字符串的数量
private long getAll(int k) {
long sum = 0l;
for (int i = 1; i <= 26 - k + 1; i++) {
sum += getByFirst(i, k);
}
return sum;
}
// 以i起始,长度为k的升序字符串的数量
private long getByFirst(int i, int k) {
long sum = 0l;
if (k - 1 > 0) {
for (int p = i; p <= 26; p++) {
for (int q = p + 1; q <= 26; q++) {
sum += getOne(q, k - 1, sum);
}
}
} else {
sum += 1;
}
return sum;
}
private long getOne(int i, int k, long rel) {
if (k == 1) {
return 1l;
} else {
for (int j = i + 1; j <= 26; j++) {
rel += getOne(j, k - 1, rel);
}
return rel;
}
}

你可能感兴趣的:(算法设计:字典序问题)