我需要从2d数组创建所有可能的字符串,以便第一个字符来自charArray[0]
,第二个字符来自charArray[1]
...最后一个字符来自{{ 1}}。
示例:
输入:
charArray[keyLength-1]
输出:
char[][] charArray =
{{'m','M','L','S','X'}
{'e','E','o','N','Z'}
{'o','G','F','r','Y'}
{'D','H','I','J','w'}};
我有一个工作解决方案,用{meoD, meoH, meoI,..., XZYJ, XZYw} //in an Array or ArrayList
中的每个字符构建一个树作为根,并且它执行深度优先字符串构造,但是JVM的内存长度小于12的charArray。我通常会这样做采用迭代方法,但charArray长度(即密钥字符串长度)是在运行时决定的,我想找到比在密钥字符串长度上写一个switch语句并手动为有限数量的密钥写出循环更完整的解决方案字符串长度。
我一直坚持我的计划的这一小部分比我想承认的更长,所以任何帮助将不胜感激!
答案 0 :(得分:0)
以下是如何解决的问题:
import java.util.ArrayList;
import java.util.List;
public class Arrays2D {
public static void main(String[] args) {
//input keys
String[][] charArray =
{{"m","M","L","S","X"},
{"e","E","o","N","Z"},
{"o","G","F","r","Y"},
{"D","H","I","J","w"}};
//print output
System.out.println(findCombinations(charArray));
}
private static List<String> findCombinations(String[][] charArray) {
List<String> prev = null;
for (int i = 0; i < charArray.length; i++) {
List<String> curr = new ArrayList<String>();
for (int j = 0; j < charArray[i].length; j++) {
if (i + 1 < charArray.length) {
for (int l = 0; l < charArray[i+1].length; l++) {
String s = charArray[i][j] + charArray[i + 1][l];
curr.add(s);
}
}
}
if (prev != null && !curr.isEmpty()) {
prev = join(prev, curr);
}
if (prev == null)
prev = curr;
}
return prev;
}
public static List<String> join(List<String> p, List<String> q) {
List<String> join = new ArrayList<String>();
for (String st1 : p) {
for (String st2 : q) {
if (st1.substring(st1.length() - 1).equals(st2.substring(0, 1))) {
String s = st1 + st2;
s = s.replaceFirst(st1.substring(st1.length() - 1), "");
join.add(s);
}
}
}
return join;
}
}
我已经检查并正确生成组合。您可以运行并查看输出。