打印字符串排列的复杂性

时间:2014-12-18 18:54:06

标签: java string permutation

这是我打印字符串排列的代码。我正在努力计算函数的时间复杂度。有人可以建议一些指示。如果有更多时间效率的方法?

import java.util.ArrayList;

public class Permutations {

    public static void main(String[] args){
        ArrayList<String> aList = permutation("ABCC");
        for(int i=0; i<aList.size(); i++){
            System.out.print(aList.get(i) + " ");
        }
    }

    public static ArrayList<String> permutation(String s) {
        // The result
        ArrayList<String> res = new ArrayList<String>();
        // If input string's length is 1, return {s}
        if (s.length() == 1) {
            res.add(s);
        } else if (s.length() > 1) {
            int lastIndex = s.length() - 1;
            // Find out the last character
            String last = s.substring(lastIndex);
            // Rest of the string
            String rest = s.substring(0, lastIndex);
            // Perform permutation on the rest string and
            // merge with the last character
            res = merge(permutation(rest), last);
        }
        return res;
    }


    public static ArrayList<String> merge(ArrayList<String> list, String c) {
        ArrayList<String> res = new ArrayList<String>();
        // Loop through all the string in the list
        for (String s : list) {
            // For each string, insert the last character to all possible postions
            // and add them to the new list
            for (int i = 0; i <= s.length(); ++i) {
                String ps = new StringBuffer(s).insert(i, c).toString();
                res.add(ps);
            }
        }
        return res;
    }
}

2 个答案:

答案 0 :(得分:0)

为了提高速度,LinkedList会更快,也会使用相同的StringBufferStringBuffer#setCharAt(int, char)。这样的事情可能是:

List<String> permutations = new ArrayList<String>(initial size); // initial size to avoid multiple arrays to be created
if (s.length() == 1) {
    permutations.add(s);
} else {
    StringBuffer sb = new StringBuffer(s);
    loop { // some kind of loop
        sb.setCharAt(0, 'a'); // do the next permutation
        permutations.add(sb.toString());
    }
}
return permutations; 

答案 1 :(得分:0)

普通merge()是O(n ^ 2)。随着复发,它似乎是O(n ^ 3)