我遇到了这个问题:
特定
{1, 2, 3}{a, b}
转换成
1a, 1b, 2a, 2b, 3a, 3b
可以有任意数量的花括号。输入将采用List>或多维数组的形式。我只能想到有多个for循环并将字符串相互相乘。
有人可以用更好的方式帮助我解决问题吗?
我试过用{}
为每个字符串设置多个循环但是如果我们有更多的花括号,这将不是一个好的解决方案
那这个呢。
"{1,2,3}{a,b}{X,Y}"
)转换为"1,2,3}{a,b}{X,Y"
String[]
:["1,2,3","a,b","X,Y"]
List
:{["1","2","3"],["a","b"],["X","Y"]}
您接下来要做的是将前两个元素相乘,并将乘法结果添加到列表的末尾。你继续这样做,直到只剩下一个元素:最终结果。所以:
{["1","2","3"],["a","b"],["X","Y"]}
成为{["X", "Y"],["1a",
"1b", "2a", "2b", "3a", "3c"]}
{["X", "Y"],["1a", "1b", "2a", "2b", "3a", "3c"]}
成为{["X1a", "X1b", "X2a", "X2b", "X3a", "X3b", "Y1a", "Y1b", "Y2a",
"Y2b", "Y3a", "Y3b"]}
public static void main(String[] args) {
String input = "{1,2,3}{a,b}{X,Y}";
System.out.println(multiplyAll(input));
}
public static String multiplyAll(String input) {
String[] parts = input.substring(1, input.length() - 1).split("\\}\\{");
List<String[]> elements = new ArrayList<>();
for (String part: parts) {
elements.add(part.split(","));
}
while (elements.size() > 1) {
String[] parts1 = elements.remove(0);
String[] parts2 = elements.remove(0);
elements.add(multiply(parts1, parts2));
}
String result = "";
for (String element: elements.get(0)) {
result += element + ",";
}
return result.substring(0, result.length() - 1);
}
public static String[] multiply(String[] parts1, String[] parts2) {
String[] result = new String[parts1.length * parts2.length];
for (int i = 0; i < parts1.length; i++) {
for (int j = 0; j < parts2.length; j++) {
result[i * parts2.length + j] = parts1[i] + parts2[j];
}
}
return result;
}