性能:JAVA置换

性能:JAVA置换,java,string,performance,permutation,hashset,Java,String,Performance,Permutation,Hashset,所以,我用这段代码生成一个单词的排列,并将其存储到哈希集中,以便以后与字典进行比较。 但是,当输入的单词有10个或更多的字母时,排列过程变得非常缓慢。除了使用置换算法,还有什么方法可以提高这个过程的性能吗 /** * Returns a HashSet of the string permutation. * * @param prefix an empty string. * @param str the string to create perm. * @return permut

所以,我用这段代码生成一个单词的排列,并将其存储到哈希集中,以便以后与字典进行比较。 但是,当输入的单词有10个或更多的字母时,排列过程变得非常缓慢。除了使用置换算法,还有什么方法可以提高这个过程的性能吗

/**
 * Returns a HashSet of the string permutation.
 *
 * @param prefix an empty string.
 * @param str the string to create perm.
 * @return permutations a HashSet of the permutation.
 */
private static HashSet<String> permutation(String prefix, String str) {
    HashSet<String> permutations = new HashSet<String>();
    int n = str.length();
    if (n == 0) {
        permutations.add(prefix);
    } else {
        for (int i = 0; i < n; i++) {
            permutations.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)));
        }
    }
    return permutations;
}
/**
*返回字符串置换的哈希集。
*
*@param前缀为空字符串。
*@param str创建perm的字符串。
*@return permutations排列的哈希集。
*/
私有静态哈希集置换(字符串前缀、字符串str){
HashSet permutations=新HashSet();
int n=str.length();
如果(n==0){
排列。添加(前缀);
}否则{
对于(int i=0;i
简短的回答: 对于置换,没有比O(n!)更复杂的了

O(n!)是我能想象到的最糟糕的时间复杂性。你找不到更有效的方法来处理排列。有关更多信息,请参阅:


长答案:

您可以通过使用Javas
StringBuffer
-Class来改进代码(而不是算法),以获得更快的结果

public static HashSet<StringBuffer> permutationNew(StringBuffer sb_prefix, StringBuffer sb_str) {
    HashSet<StringBuffer> permutations = new HashSet<>();
    int n = sb_str.length();
    if (n == 0) {
        permutations.add(sb_prefix);
    } else {
        for (int i = 0; i < n; i++) {
            permutations.addAll(permutationNew(sb_prefix.append(sb_str.charAt(i)), new StringBuffer(sb_str.substring(0, i)).append(sb_str.substring(i + 1, n))));
        }
    }
    return permutations;
}
如果有许多方法引用您的置换方法,请围绕优化的方法创建一个包装器:

private static HashSet<String> permutation(String prefix, String str) {
    HashSet<StringBuffer> permutations = permutationNew(new StringBuffer(prefix), new StringBuffer(str);
    //create new HashSet<String> using permutations-HashSet and return it...
私有静态哈希集置换(字符串前缀,字符串str){
HashSet permutations=permutationNew(新StringBuffer(前缀),新StringBuffer(str);
//使用置换哈希集创建新哈希集并返回它。。。

指定一个初始容量,该容量与
哈希集中的预期条目数相匹配,这样它就不必一直扩展。算法的复杂度为O(n!).这可能是最糟糕的复杂性。10次需要3628800steps@Henrik嗯,问题是我不知道预期的数字,可能是1000000或100000000,这取决于输入字符串的长度。我不确定使用哈希集是否是最佳选择。@TianchengXu:嗯,当然可以根据字符串的长度进行计算。无论如何,仅仅是一个近似值可能会减少运行时间。如果一个映射包含很多条目的话,调整它的大小以容纳比预期更多的条目的代价可能会相当高。@VladBochenin,它的意思是生成输入字符串的每一个组合,并在以后检查哪个是英语单词。所以…我想最好的方法是使用某种算法它可以消除无用的组合。
private static HashSet<String> permutation(String prefix, String str) {
    HashSet<StringBuffer> permutations = permutationNew(new StringBuffer(prefix), new StringBuffer(str);
    //create new HashSet<String> using permutations-HashSet and return it...