一道Java笔试题,求解???
有一个String[100]的数组,每个值的长度都为2的整数倍,例如String[0]="AA",String[1]="AABB",String[2]="BB",String[3]="CC",String[4]="CCBB",String[5]="BBAA"...,请写一段程序,将这个数组的内容以树形结构打印出来。
------解决方案--------------------
应该是这个效果,给我分吧~
========================
public static void main(String[] args) {
String[] strAry = new String[]{"aa","bb","aabb","aabbcc","bbdd","bbee","ffcc","ffccaa","aadd","aaff"};
for(int i=0; i<strAry.length; i++){
test(i,strAry,"");
}
}
private static void test(int start,String[] strAry,String pre) {
if(strAry[start]==null) return;
String str = strAry[start];
strAry[start] = null;
System.out.println(pre+str);
for(int i=start+1; i<strAry.length; i++){
if(strAry[i] != null && strAry[i].startsWith(str)){
test(i,strAry,pre+" ");
}
}
}