java 字符串排列组合

public static LinkedList permutation(String str) {
        
        LinkedList linkedString = new LinkedList();   
        if (str.length() <= 1) {  
            linkedString.add(str);  
            return linkedString;  
        }   
        for (int i = 0; i < str.length() ; i++) {  
            char ch = str.charAt(i);  
            //consider the case in which the characters may be duplicated.  
            if (i > 0 && ch == str.charAt(i - 1)) {  
                continue;  
            }  
            String newStr = remove(str, i);  
            LinkedList newStrList= permutation(newStr);   
            for (int j = 0; j < newStrList.size(); j++) {  
                linkedString.add(ch + newStrList.get(j));  
            }  
        }  
        return linkedString;  
    }  
    //remove the ith character from the string  
    public static String remove(String str, int i) {  
        if (i == 0) return str.substring(1, str.length());  
        if (i == str.length() - 1) return str.substring(0, i );  
        return str.substring(0, i) + str.substring(i + 1, str.length());  
    } 

你可能感兴趣的:(java 字符串排列组合)