最近参加笔试比较多,遇到这道题:
题目: 将一个交错数据合并为一个一维数组
输入: strJaggedArray[][], 由多个一维数组(长度不定,个数不定)组成的交错数组
输出: strArray[], 由strJaggedArray[r][c]中的元素以"&"为分隔符拼合而成, 是strJaggedArray中数组元素的无重复组合(不考虑顺序)
举例:
输入: strJaggedArray[0]=new string[] {"we","are","student"};
strJaggedArray[1]=new string[] {"say","what"};
输出: strArray[]={"we&say","we&what","are&say","are&what","student&say","student&what"}
输入: strJaggedArray[0]=new string[] {"cs","app"};
strJaggedArray[1]=new string[] {"good","cool","dev"};
strJaggedArray[2]=new string[] {"king","of","the","world"};
输出: strArray[]={"cs&good&king","cs&good&of","cs&good&the","cs&good&world","cs&cool&king","cs&cool&of","cs&cool&the","cs&cool&world",...}
代码:
public class ExchangeArray { public static void main(String args[]){ String a[][]=new String[4][]; a[0]=new String[]{"cs","app"}; a[1]=new String[]{"good","cool","dev"}; a[2]=new String[]{"king","of","the","world"}; a[3]=new String[]{"hello","every","one","how","are","you"}; for(int i=0;i<a.length;i++){ System.out.println(); for(int j=0;j<a[i].length;j++){ System.out.print(a[i][j]+" "); } } System.out.println("the result is:"); String b[]=exchange(a); for(int i=0;i<b.length;i++){ System.out.print(b[i]+" "); } } public static String[] exchange(String exchange[][]){ String result[][]=exchangeArray(exchange); return result[0]; } public static String[][] exchangeArray(String exchange[][]){ if(exchange.length>=2){ int len1=exchange[0].length; int len2=exchange[1].length; int len=len1*len2; String temp []=new String[len]; int index=0; for(int i=0;i<len1;i++){ for(int j=0;j<len2;j++){ temp[index++]=exchange[0][i]+"&"+exchange[1][j]; } } String copy[][]=new String[exchange.length-1][]; for(int i=2;i<exchange.length;i++){ copy[i-1]=exchange[i]; } copy[0]=temp; return exchangeArray(copy); }else{ return exchange; } } }