树分析器的递归字符串

时间:2015-09-24 15:19:00

标签: java string algorithm arraylist tree

目前我正在尝试实现构建树结构的递归解决方案,我已将String拆分为例如

input: "(3 + 5)" 
Output: [1, 3], [1, +], [1, 5]
input: "3 + 5"
Output [0, 3], [0, +], [0, 5]

这是表示开放式括号表达式(第一个输出) 和整个表达式(第二个输出)。关于如何递归调用这个问题,我有点困惑(和睡眠不足),所以如果输入更大,它会不断创建子树?有任何想法吗?或链接到文档:)

public Node parseStringToTree(String str)
{
    str = str.replaceAll(" ", "");

    ArrayList<Character> chars = new ArrayList<Character>();
    ArrayList<Integer> depths = new ArrayList<Integer>();

    int openCount = 0;
    int openClose = 0;

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (c == '(') {
            openCount++;
        } else if (c == ')') {
            openClose++;
        } else {
            int currentDepth = openCount - openClose;
            chars.add(c);
            depths.add(currentDepth);
        }
    }

    for (int i = 0; i < chars.size(); i++) {
        int depth = depths.get(i);
        char c = chars.get(i);

        System.out.println("[" + depth + ", " + c + "]");
    }

    return root;
}

0 个答案:

没有答案