题目
编程题(20分钟)
将一个交错数据合并为一个一维数组
输入: 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 StrJaggedArray {
public static void main(String[] args) {
String[][] strJaggedArray = new String[2][3];
String[] s1 = {"we","are","student"};
strJaggedArray[0] =s1;
String[] s2 = {"say","what"};
strJaggedArray[1] = s2;
Object[] strings = strJaggedArray(strJaggedArray);
}
private static Object[] strJaggedArray(String[][] strJaggedArray) {
ArrayList<String> all = new ArrayList<>();
HashSet<String> res = new HashSet<>();
for ( String[] sArr: strJaggedArray) {
for (String string : sArr) {
all.add(string);
}
}
int p1 = 0;
for ( String[] sArr: strJaggedArray) {
for (int i = 0; i < sArr.length; i++) {
for (int j = 0; j < all.size(); j++) {
if(j < p1 || j >= p1 + sArr.length){
if(sArr[i].compareTo(all.get(j)) > 0){
res.add(sArr[i] + "&" + all.get(j) );
}else{
res.add(all.get(j) + "&" + sArr[i] );
}
}
}
}
p1 = p1 + sArr.length;
}
System.out.println(res);
return res.toArray();
}
}