1:剑指offer, 通过递归,遍历到最底层开始打印。
package com.li.String; /** * @program: GradleTestUseSubModule * @author: Yafei Li * @create: 2018-07-21 15:49 * Java 中,怎么打印出一个字符串的所有排列 **/ public class PrintStringSort { public static void main(String[] args){ String str="abcd"; char[] chars = str.toCharArray(); int low=0; for (int i = 0; i <chars.length; i++) { char temp = chars[i]; chars[i]=chars[0]; chars[0]=temp; print(chars,low); } } private static void print(char[] chars, int low) { if (low == chars.length-1) { for (int i = 0; i < chars.length; i++) { System.out.print(chars[i]); } System.out.println(""); } for (int i = low+1; i < chars.length; i++) { char temp=chars[i]; chars[i] = chars[low+1]; chars[low+1]=temp; print(chars,low + 1); char temp1=chars[i]; chars[i] = chars[low+1]; chars[low+1]=temp1; } } }
结果:从后往前改变
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cabd
cadb
cbad
cbda
cdba
cdab
dabc
dacb
dbac
dbca
dcba
dcab
2: 打印一个字符串的字典排序,前面n个数相同,后面n个数相同,网易考试题。
package com.li.wangYi; import java.util.LinkedHashSet; import java.util.Set; /** * @program: GradleTestUseSubModule * @author: Yafei Li * @create: 2018-07-21 15:49 * Java 中,怎么打印出一个字符串的所有排列 **/ public class Ques3 { static Set<String> set = new LinkedHashSet<>(); public static void main(String[] args){ String str="aaazzz"; char[] chars = str.toCharArray(); int low=0; for (int i = 0; i <chars.length; i++) { char temp = chars[i]; chars[i]=chars[0]; chars[0]=temp; print(chars,low); } for (String s : set) { System.out.println(s); } } private static void print(char[] chars, int low) { StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < chars.length; i++) { stringBuffer.append(chars[i]); } set.add(stringBuffer.toString()); stringBuffer=null; for (int i = low+1; i < chars.length; i++) { char temp=chars[i]; chars[i] = chars[low+1]; chars[low+1]=temp; print(chars,low + 1); char temp1=chars[i]; chars[i] = chars[low+1]; chars[low+1]=temp1; } } }
打印出aaazzz的字典顺序字符串,结果,从前往后改变。
aaazzz
aazazz
aazzaz
aazzza
azaazz
azazaz
azazza
azzaaz
azzaza
azzzaa
zaaazz
zaazaz
zaazza
zazaaz
zazaza
zazzaa
zzaaaz
zzaaza
zzazaa
zzzaaa