【问题标题】:Tree structure as string - how to match nested braces?树结构作为字符串 - 如何匹配嵌套大括号?
【发布时间】:2011-07-07 04:27:00
【问题描述】:

我设置了一个树形结构,并希望将其保存到字符串中/从字符串中读取,并使用最少的文本(因此 XML 序列化已被淘汰)。我为此设置了一个简单的(或者我认为是这样的)结构,但不知道如何读取它,所以我的结构很可能不得不改变。让我用一个例子来演示一下。

我的树由 X,Y 坐标组成,如下例所示:

[a,b]
  |-----|
[c,d] [e,f]
        |-----|-----|
      [g,h] [i,j] [k,l]

当我运行我的算法将这棵树变成一个字符串时,我得到以下输出:

a,b(c,d()e,f(g,h()i,j()k,l()))

这里是我正在使用的代码:

public string SerializeMe()
{
    StringBuilder ret = new StringBuilder(this.Value.ToString())
    ret.Append("(");
    foreach (SimpleTreeNode<T> child in _Children)
    {
        ret.Append(child.SerializeMe());
    }
    ret.Append(")");
    return ret.ToString();
}

这很好用,但现在我无法将字符串解析回我的树结构。我可以将子字符串获取到第一个左大括号并将其转换为节点的值,但我不确定如何将字符串的其余部分拆分为子字符串。有什么方法可以轻松找到一个左大括号,然后找到它的右大括号?我研究了一些复杂的正则表达式,我无法正常工作,很快就完全迷失了。

有人有什么想法吗?

编辑:
这是我到目前为止的代码:

public static SimpleTreeNode<SPoint> ParsePointTree(string input)
{
    //if the input string is empty, there is no node here. Return null.
    if (string.IsNullOrEmpty(input)) return null;
    else
    {
        //get the value from the first part of the string
        string valString = input.Substring(0, input.IndexOf('('));
        SPoint value = (SPoint)valString;
        SimpleTreeNode<SPoint> node = new SimpleTreeNode<SPoint>(value);

        //now we have the child nodes enclosed in brackets
        string innerstring = input.Substring(input.IndexOf('('));

        List<string> children = new List<string>();
        // how do we split innerstring into siblings?? //

        foreach (string child in children)
        {
            node.Children.Add(SimpleTreeNode<SPoint>.ParsePointTree(child));
        }

        return node;
    }
}

我遇到的问题是,我将得到一个必须分成兄弟姐妹的字符串。在上面的示例中,c,de,f 是兄弟姐妹,以 (c,d()e,f(g,h()i,j()k,l())) 的形式表示。我需要将此字符串拆分为c,d()e,f(g,h()i,j()k,l()),这是我卡住的地方。

【问题讨论】:

  • 另外,请向我们展示您的解析代码,而不是您的序列化代码...
  • 马克·艾略特说得对。请注意,您以递归方式构建了输出。如果您递归地解析它,并且让每个解析级别在您发出的 (...) 对中构造子树,这可能是最简单的。
  • ...但是在我们查看您的序列化代码时,请考虑使用StringBuilder
  • 感谢 StringBuilder 的建议,但我不明白您对我的解析代码的期望。关键是,我不知道该怎么做,因此我还没有解析代码......我想我必须递归解析它,但我遇到的问题是分裂兄弟节点.我可能应该在我的问题中更清楚地说明这一点。

标签: c# algorithm parsing tree


【解决方案1】:

您可以使用堆栈和 2 个局部变量来解析这样的字符串。如果您使用广度优先遍历而不是深度优先对树进行序列化,则不需要堆栈(顺便说一句,在任何一种情况下都不必递归)。

递归解决方案仅利用调用堆栈,并可能导致堆栈溢出 - see here for a better explanation 为什么这不是最好的方法。

foreach (char c in "a(c()e(g()i()k()))")
{
    if (c == '(')
    {
        Stack.Push(Parent);
        Parent = Child;
    }
    else if (c == ')')
    {
        Child = Parent;
        Parent = Stack.Pop();
    }
    else
    {
        Child = new SimpleTreeNode() { Value = c };
        Parent.Children.Add(Child);
    }
}

【讨论】:

  • 解决方案不完全是这样,因为每个节点的值不止一个字符,但方法的主体是我最终使用的。而且我的节点上确实有一个父属性,所以我也不需要堆栈。感谢您的提示
  • 我编辑了关于父属性的注释 - 以消除按特定顺序对树进行编码所需的堆栈。您可能想尝试在示例中向 [c,d] 添加一些子项,以确保它仍然正常工作!
【解决方案2】:

类似这样的东西(伪代码):

function parse() =
    label = read_until('(',')');
    read_char('(')
    children = []
    while not peek_char(')') do
        child = parse()
        children.add(child)
    read_char(')')
    return new Node(label,children)
  • read_until(...) 读取直到,但不包括,给定的字符。
  • read_char(c) 读取一个字符,如果不匹配则会引发错误。
  • peek_char(c) 查看下一个字符,并返回一个表示是否匹配的真值。

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多