Java输出字符串的全排列

it2026-06-06  6

标题:Java输出字符串的全排列

/** * 全排列 【待续】 * @author dell * */ public class TestAllSort { /** * int[] * 输出ABCD后,不会输出AB,只会输出DC * @param s * @param count * @param a */ public void allSort(String s, int count, int[] a) { if(count >= 4) { System.out.println(); return ; }else { for(int i = 0; i < 4; i++) { if(a[i] != -1) { //Arrays.fill(a, -1); == -1 System.out.print(s.charAt(i) + ""); a[i] = -1; this.allSort(s, count + 1, a); a[i] = 0; } } } } @Test public void test() { String s = "ABCD"; int count = 0; int[] a = new int[s.length()]; // this.allSort(s, count, a); } /** * char[] 不行,ABCD后,ABD_,四号位仍然没有赋值,所以下次取得仍然是D * @param s * @param count * @param a */ public void allSort02(String s, int count, char[] a) { if(count >= 4) { for(int i = 0; i < a.length; i++) { System.out.print(a[i]); } System.out.println(); return ; }else { for(int i = 0; i < 4; i++) { if(a[i] == 0) { a[count] = s.charAt(i); this.allSort02(s, count + 1, a); a[count] = 0; } } } } @Test public void test02() { String s = "ABCD"; int count = 0; char[] a = new char[s.length()]; char ch = '0'; int b = ch; //ch初始化为0时,b就是0; ch初始化为 '0'时,b为48 // System.out.println(b); // System.out.println(a[0] == 0); //true char的默认值为0 不是字符0 // this.allSort02(s, count, a); } public void allSort03(String s, int count, int[] a) { if(count >= 4) { for(int i = 0; i < a.length; i++) { //0 1 3 2 System.out.print(s.charAt(a[i])); } System.out.println(); return ; }else { for(int i = 0; i < a.length; i++) { if(a[i] == -1) { //标志数组未赋值 a[i] = count; this.allSort03(s, count + 1, a); a[i] = -1; } } } } @Test public void test03() { String s = "ABCD"; int count = 0; int[] a = new int[s.length()]; Arrays.fill(a, -1); this.allSort03(s, count, a); } }
最新回复(0)