字符串全排列(permutation)

Reference:

http://www.cnblogs.com/sujz/archive/2011/06/16/2082831.html

问题:给定字符串S,生成该字符串的全排列。

方法1:依次从字符串中取出一个字符作为最终排列的第一个字符,对剩余字符组成的字符串生成全排列,最终结果为取出的字符和剩余子串全排列的组合。

 1 public static void main(String[] args) {
 2         Main so = new Main();
 3         System.out.println("method 1:");
 4         so.permutation("","ABA");
 5     }
 6     public void permutation(String prefix,String s){
 7         if(s==null||s.length()==0)
 8             System.out.println(prefix);
 9         for(int i=0;i<s.length();i++){
10             permutation(prefix+s.charAt(i), s.substring(0, i)+s.substring(i+1,s.length()));
11         }
12     }

优点:该方法易于理解,但无法移除重复的排列,如:s="ABA",会生成两个“AAB”。

method 1:
ABA
AAB
BAA
BAA
AAB
ABA

 

方法2:利用交换的思想,具体见实例,但该方法不如方法1容易理解。

 

 1 package POJ;
 2 
 3 import java.util.HashMap;
 4 
 5 public class Main {
 6 
 7     /**
 8      * 
 9      * 9.4 Write a method to compute all permutations of a string.
10      * 
11      * 
12      */
13     public static void main(String[] args) {
14         Main so = new Main();
15         System.out.println("method 2:");
16         HashMap<String, Integer> hs=new HashMap<String, Integer>();
17         so.permutation2("AABB", 0, 3,hs);
18     }
19 
20     public void permutation2(String s, int startIndex, int endIndex,HashMap<String, Integer> hs) {
21         if (startIndex == endIndex) {
22             if(!hs.containsKey(s)){
23                 hs.put(s, 1);
24                 System.out.println(s);
25             }
26         }
27         for (int j = startIndex; j <= endIndex; j++) {
28             if ((s.charAt(j) == s.charAt(startIndex)) && (j != startIndex))
29                 continue;
30             s = swap(s, startIndex, j);
31             permutation2(s, startIndex + 1, endIndex,hs);
32             s = swap(s, startIndex, j);
33         }
34     }
35 
36     public String swap(String s, int i, int j) {
37         char[] char_s = s.toCharArray();
38 
39         char temp = char_s[i];
40         char_s[i] = char_s[j];
41         char_s[j] = temp;
42 
43         s = String.copyValueOf(char_s);
44         return s;
45     }
46 }

运行结果:

method 2:
AABB
ABAB
ABBA
BAAB
BABA
BBAA

原Reference里的那个哥们儿的代码有点问题,他的代码用java实现后只能完成类似于ABCD,AABC等string的无重复全排列,而无法做到AABB这种类型的无重复全排列。

 

posted @ 2014-08-10 18:34  Phoebe815  阅读(415)  评论(0编辑  收藏  举报