Faster string permutation

≡放荡痞女 提交于 2019-12-25 04:59:11

问题


I have permutation methods

public void permute(String str) {
    permute(str.toCharArray(), 0, str.length() - 1);
}

private void permute(char[] str, int low, int high) {
    if (low == high) {
        writeIntoSet(new String(str, 0, length));
    } else {
        for (int i = low; i <= high; i++) {
            char[] x = charArrayWithSwappedChars(str, low, i);
            permute(x, low + 1, high);
        }
    }
}

private char[] charArrayWithSwappedChars(char[] str, int a, int b) {
    char[] array = str.clone();
    char c = array[a];
    array[a] = array[b];
    array[b] = c;
    return array;
}

But when I put string, which is 10 letters length into this method, it makes 10! combinations and it takes so much time. Is there any possibility how to make it faster?

EDIT

I need to make permutations from 10 letters, but after that, I search these "words" in dictionary. For example I have - CxRjAkiSvH and I need words CAR, CARS, CRASH etc. Is there any performance option?


回答1:


There are existing algorithms for generating permutations which may be slightly more efficient than the one you're using, so you could take a look at one of those. I've used the Johnson-Trotter algorithm in the past, which gets a slight speed up by making the minimum change possible to get the next permutation each time. I don't know what kind of constraints you have to work within, but if you don't have to use Java it might be better not to. It simply won't be the fastest for this. Especially if your algorithm is using recursion. As someone else has suggested, if you're sticking with this algorithm you might be best served to move away from the recursive approach and try using a loop.




回答2:


For a string of 10 characters, there are 10! permutations, there's no two ways around that. You might be able to make it slightly faster by appending to StringBuffers instead, or using a char[] manually.



来源:https://stackoverflow.com/questions/10962682/faster-string-permutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!