Parsing Nested Bracket String in java

时间:2015-04-29 00:23:56

标签: java parsing recursion stack brackets

I want to parse strings with (nested) brackets and values like:

A,(B,C),(D,(B,D),X)

I want the inner tuples as f.ex ArrayList, like ArrayList(B,C) or ArrayList(D,ArrayList(B,D)).

My first idea was to use a Stack, but i have problems when i have a tuple in a tuple and then after the inner tuple comes another value, like (Z,(A,B),C).

public static ArrayList<Object> parse(String str, ArrayList<Object> result) {
    ArrayList<Object> tmp = result;
    if (str.length() == 0) {
        return tmp;
    } else if (str.charAt(0) == '(') {
        ArrayList<Object> al = new ArrayList<Object>();
        tmp.add(al);
        str = str.substring(1, str.length());
        return parse(str, tmp);
    }else if(str.charAt(0) == ',')
    {
        str = str.substring(1,str.length());
        return parse(str,tmp);
    }
    else {
        ArrayList<String> al = new ArrayList<String>();
        al.add(""+str.charAt(0));
        tmp.add(al);

        str = str.substring(1, str.length());
        return parse(str,tmp);
    }
}

public static void main(String[] args) {
    ArrayList<Object> al = new ArrayList<Object>();
    System.out.println(parse("A,(B),(C,(D,E),F)",al));  
}

Output:

[[A], [], [B], [)], [], [C], [], [D], [E], [)], [F], [)]]

1 个答案:

答案 0 :(得分:0)

使用堆栈时会遇到什么问题?您应该能够使用堆栈来模拟递归算法来执行此操作。我认为这是递归构建ArrayLists。在基本情况下,当遇到')'或字符串结尾时返回arrayList,如果遇到一个字符将其添加到列表中,如果遇到'('你应该递归。你必须确保对象类型足够抽象,可以应用于ArrayLists和您读取的对象。