简体   繁体   English

多个字符串相乘

[英]Multiply multiple strings

I came across this question :我遇到了这个问题:

Given给定的

{1, 2, 3}{a, b} 

convert into转换为

1a, 1b, 2a, 2b, 3a, 3b

There can be any number of curly braces.可以有任意数量的花括号。 Input will be in the form of List> or a multidimensional array.输入将采用 List> 或多维数组的形式。 I can only think of having multiple for loops and multiplying the strings with each other.我只能想到有多个 for 循环并将字符串彼此相乘。

Can someone help me with question in a better way?有人可以以更好的方式帮助我解决问题吗?

I have tried having multiple loops for the each string with {} but that will not a good solution in case we have more number of curly braces我试过用{}对每个字符串进行多个循环,但如果我们有更多的花括号,这不是一个好的解决方案

What about this.那这个呢。

  • First you convert the input ( "{1,2,3}{a,b}{X,Y}" ) to "1,2,3}{a,b}{X,Y"首先,您将输入 ( "{1,2,3}{a,b}{X,Y}" ) 转换为"1,2,3}{a,b}{X,Y"
  • Then you convert this to an String[] : ["1,2,3","a,b","X,Y"]然后将其转换为String[] : ["1,2,3","a,b","X,Y"]
  • Finally, you convert this to a List : {["1","2","3"],["a","b"],["X","Y"]}最后,将其转换为List{["1","2","3"],["a","b"],["X","Y"]}

What you do next is that you multiply the first two elements and add the result of the multiplication to the end of the list.接下来要做的是将前两个元素相乘并将乘法的结果添加到列表的末尾。 You continue doing this, until there is just one element left: the final result.你继续这样做,直到只剩下一个元素:最终结果。 So:所以:

  • {["1","2","3"],["a","b"],["X","Y"]} becomes {["X", "Y"],["1a", "1b", "2a", "2b", "3a", "3c"]} {["1","2","3"],["a","b"],["X","Y"]}变成{["X", "Y"],["1a", "1b", "2a", "2b", "3a", "3c"]}
  • {["X", "Y"],["1a", "1b", "2a", "2b", "3a", "3c"]} becomes {["X1a", "X1b", "X2a", "X2b", "X3a", "X3b", "Y1a", "Y1b", "Y2a", "Y2b", "Y3a", "Y3b"]} {["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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM