多个字符串相乘

时间:2019-04-14 12:13:47

标签: java string algorithm data-structures

我遇到了这个问题:

给予

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

转换为

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

可以有任意多个花括号。输入将采用List>或多维数组的形式。 我只能想到有多个for循环并将字符串彼此相乘。

有人可以更好地帮助我解决问题吗?

我尝试使用{}为每个字符串设置多个循环,但是如果我们有更多的花括号,那将不是一个好的解决方案

1 个答案:

答案 0 :(得分:0)

那怎么办?

  • 首先,您将输入("{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;
    }