import java.util.ArrayList;<br />import java.util.List;<br />/**<br /> * 求字串的全排列<br /> *<br /> * @author wenin819<br /> *<br /> */<br />public class Arrange {<br />/**<br /> * 判斷調用求排列的主要方法<br /> */<br />public static List<String> arrange(String input){<br />if(null == input || 0 == input.length()){<br />System.out.println("輸入為空白!結果也為空白!");<br />return null;<br />}<br />List<String> rsList= new ArrayList<String>();<br />arrangeItem(new StringBuffer(input), input.length() - 1, rsList);<br />return rsList;<br />}<br />/**<br /> * 求排列的主要方法<br /> */<br />public static void arrangeItem(StringBuffer input, int end,<br />List<String> rsList) {<br />if (0 == end) {<br />rsList.add(new String(input));<br />return;<br />}<br />for (int i = 0; i <= end; i++) {<br />swap(input, i, end);<br />arrangeItem(input, end - 1, rsList);<br />swap(input, i, end);<br />}<br />}<br />/**<br /> * 置換StringBuffer字串中i和j位置上的字元<br /> */<br />private static void swap(StringBuffer word, int i, int j) {<br />if (i == j)<br />return;<br />char temp;<br />temp = word.charAt(i);<br />word.setCharAt(i, word.charAt(j));<br />word.setCharAt(j, temp);<br />}<br />/**<br /> * 測試<br /> */<br />public static void main(String args[]) {<br />String input = new String("abcd");<br />if(args.length > 0)<br />input = args[0];<br />List<String> rsList = arrange(input);<br />System.out.println(input+"的排列總數為:" + rsList.size() + "/n排列分別為:");<br />for (int i = 0; i < rsList.size(); i++) {<br />System.out.println(rsList.get(i));<br />}<br />}<br />}<br />