生命之风的低语
Whispers in the Wind of Life.

java - 生成字典序上最大的字符串

2025-10-14 06:27:56

问题是在给定一些字符串 s 的情况下生成字典上最大的字符串。因此,目标是从 s 中找到字典顺序上最大的、唯一的(无重复)子字符串 s1。如果 s1 的字符数比 s2 多,或者如果长度相等,则我们说某个子序列 s1 大于另一个子序列 s2。

输入输出如下:

输入是:ba bab

输出是:巴

第二个输入是: nlhthgrfdnnlprjtecpdr t higjoqdejsfka soc tjijaoebql r gaiakfsbljm p ib k id j srtk g r d n q sk nb arp a bgokbsr fhm eklr le

第二个输出是:tsocrpkijgdqnbafhmle

这是我为我的 java 代码编写的,但我的代码在第二个测试用例中失败了。我也很难理解为什么第二个输出不是 tsrqponmlkjihgfedcba。有人可以提供修复甚至Java代码的建议吗?

我认为该算法必须比生成所有可能的唯一字符串、对它们进行排序并找到字典上最大的字符串更有效。

为了使问题更清楚,如果输入是 babab,那么所有可能的唯一组合将是 b、a、ba、ab。并且输出将是 ba,因为它是最长的并且在字典上大于 ab。

注意:这不是家庭作业。

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class mostBeautiful {

final static int MAX = 1000000;

static String[] permute;

static void permutation(String prefix, String str, int counter) {

int n = str.length();

//System.out.println("n is: "+ n);

if (n == 0) {

permute[counter] = prefix;

} else {

for (int i = 0; i < n; i++) {

//System.out.println("str is: "+ str);

permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n), counter++);

}

}

}

public static void main(String[] args) throws IOException {

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

String s = bf.readLine();

char[] unique = new char[26];

int counter = 0;

String answer = "";

//System.out.println("s is: " + s);

int ascii = 0;

final int asciiAVal = 97;

final int asciiZVal = 122;

for (int i = 0; i < s.length(); i++) {

ascii = (int)s.charAt(i);

if (ascii < asciiAVal || ascii > asciiZVal) {

continue;

}

char ch = s.charAt(i);

unique[ch - 'a'] = ch;

}

String result = "";

for (int j = 25; j >= 0; j--) {

result += unique[j];

}

result = result.trim();

System.out.println(result);

int size = result.length() * (result.length() - 1);

permute = new String[size];

permutation("", result, counter);

for (int i = 1; i < size; i++) {

if (permute[i].compareTo(permute[i - 1]) > 0){

answer = permute[i];

} else {

answer = permute[i - 1];

}

}

System.out.println("answer is: " + answer);

}

}