Generating all permutations of a given string

前端 未结 30 1613
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  温柔的废话
    2020-11-21 06:49

    Well here is an elegant, non-recursive, O(n!) solution:

    public static StringBuilder[] permutations(String s) {
            if (s.length() == 0)
                return null;
            int length = fact(s.length());
            StringBuilder[] sb = new StringBuilder[length];
            for (int i = 0; i < length; i++) {
                sb[i] = new StringBuilder();
            }
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                int times = length / (i + 1);
                for (int j = 0; j < times; j++) {
                    for (int k = 0; k < length / times; k++) {
                        sb[j * length / times + k].insert(k, ch);
                    }
                }
            }
            return sb;
        }
    

提交回复
热议问题