将字符串列表映射为对象的分层结构

10

这不是一道作业题。这个问题是在面试测试中问我的一个朋友的。

我有一个从文件中读取的行列表作为输入,每行开头都有一个标识符,例如(A,B,NN,C,DD)。根据标识符,我需要将记录映射到单个对象A中,其中包含对象的层次结构。

enter image description here

层次结构描述: 每个A可以有零个或多个B类型。 每个B标识符可以有零个或多个NN和C作为子级。同样,每个C段落可以有零个或多个NN和DD子级。每个DD可以有零个或多个NN作为子级。

映射类及其层次结构:

所有类都将具有“value”,以保存当前行的字符串值。

**A - will have list of B**

    class A {
        List<B> bList;
        String value;

        public A(String value) {
            this.value = value;
        }

        public void addB(B b) {
            if (bList == null) {
                bList = new ArrayList<B>();
            }
            bList.add(b);
        }
    }


**B - will have list of NN and list of C**

    class B {
            List<C> cList;
            List<NN> nnList;
            String value;
                public B(String value) {
                this.value = value;
            }
                public void addNN(NN nn) {
                if (nnList == null) {
                    nnList = new ArrayList<NN>();
                }
                nnList.add(nn);
            }
                public void addC(C c) {
                if (cList == null) {
                    cList = new ArrayList<C>();
                }
                cList.add(c);
            }
        }

**C - will have list of DDs and NNs**

    class C {
            List<DD> ddList;
            List<NN> nnList;
            String value;
            public C(String value) {
                this.value = value;
            }
            public void addDD(DD dd) {
                if (ddList == null) {
                    ddList = new ArrayList<DD>();
                }
                ddList.add(dd);
            }
            public void addNN(NN nn) {
                if (nnList == null) {
                    nnList = new ArrayList<NN>();
                }
                nnList.add(nn);
            }
        }

**DD - will have list of NNs**

    class DD {
            String value;
            List<NN> nnList;
            public DD(String value) {
                this.value = value;
            }
            public void addNN(NN nn) {
                if (nnList == null) {
                    nnList = new ArrayList<NN>();
                }
                nnList.add(nn);
            }
        }

**NN- will hold the line only**

    class NN {
        String value;

        public NN(String value) {
            this.value = value;
        }
    }

我到目前为止所做的:

public A parse(List<String> lines)方法读取输入列表并返回对象A。由于可能有多个B,因此我创建了一个单独的'parseB'方法来解析每个出现的B

parseB方法中,循环遍历i = startIndex + 1 to i < lines.size()并检查行的开头。如果检测到"NN"的出现,就将其添加到当前的B对象中。如果检测到"C",则调用另一个方法parseC。当我们在开头检测到"B"或"A"时,循环会终止。

parseC_DD中使用类似的逻辑。

public class GTTest {    
    public A parse(List<String> lines) {
        A a;
        for (int i = 0; i < lines.size(); i++) {
            String curLine = lines.get(i);
            if (curLine.startsWith("A")) { 
                a = new A(curLine);
                continue;
            }
            if (curLine.startsWith("B")) {
                i = parseB(lines, i); // returns index i to skip all the lines that are read inside parseB(...)
                continue;
            }
        }
        return a; // return mapped object
    }

    private int parseB(List<String> lines, int startIndex) {
        int i;
        B b = new B(lines.get(startIndex));
        for (i = startIndex + 1; i < lines.size(); i++) {
            String curLine = lines.get(i);
            if (curLine.startsWith("NN")) {
                b.addNN(new NN(curLine));
                continue;
            }
            if (curLine.startsWith("C")) {
                i = parseC(b, lines, i);
                continue;
            }
            a.addB(b);
            if (curLine.startsWith("B") || curLine.startsWith("A")) { //ending condition
                System.out.println("B A "+curLine);
                --i;
                break;
            }
        }
        return i; // return nextIndex to read
    }

    private int parseC(B b, List<String> lines, int startIndex) {

        int i;
        C c = new C(lines.get(startIndex));

        for (i = startIndex + 1; i < lines.size(); i++) {
            String curLine = lines.get(i);
            if (curLine.startsWith("NN")) {
                c.addNN(new NN(curLine));
                continue;
            }           

            if (curLine.startsWith("DD")) {
                i = parseC_DD(c, lines, i);
                continue;
            }

            b.addC(c);
            if (curLine.startsWith("C") || curLine.startsWith("A") || curLine.startsWith("B")) {
                System.out.println("C A B "+curLine);
                --i;
                break;
            }
        }
        return i;//return next index

    }

    private int parseC_DD(C c, List<String> lines, int startIndex) {
        int i;
        DD d = new DD(lines.get(startIndex));
        c.addDD(d);
        for (i = startIndex; i < lines.size(); i++) {
            String curLine = lines.get(i);
            if (curLine.startsWith("NN")) {
                d.addNN(new NN(curLine));
                continue;
            }
            if (curLine.startsWith("DD")) {
                d=new DD(curLine);
                continue;
            }       
            c.addDD(d);
            if (curLine.startsWith("NN") || curLine.startsWith("C") || curLine.startsWith("A") || curLine.startsWith("B")) {
                System.out.println("NN C A B "+curLine);
                --i;
                break;
            }

        }
        return i;//return next index

    }
public static void main(String[] args) {
        GTTest gt = new GTTest();
        List<String> list = new ArrayList<String>();
        list.add("A1");
        list.add("B1");
        list.add("NN1");
        list.add("NN2");
        list.add("C1");
        list.add("NNXX");
        list.add("DD1");
        list.add("DD2");
        list.add("NN3");
        list.add("NN4");
        list.add("DD3");
        list.add("NN5");
        list.add("B2");
        list.add("NN6");
        list.add("C2");
        list.add("DD4");
        list.add("DD5");
        list.add("NN7");
        list.add("NN8");
        list.add("DD6");
        list.add("NN7");
        list.add("C3");
        list.add("DD7");
        list.add("DD8");
        A a = gt.parse(list);
            //show values of a 

    }
}

我的逻辑不正常。 你能想到其他方法吗?你有任何建议或改进方法吗?


6
我的逻辑不起作用。这句话传达了零信息。请解释您期望得到什么结果,您得到了什么,以及为什么您认为应该得到前者而不是后者。 - n. m.
3个回答

8

使用对象层次结构:


    public interface Node {
        Node getParent();
        Node getLastChild();
        boolean addChild(Node n);
        void setValue(String value);
        Deque  getChildren();
    }

    private static abstract class NodeBase implements Node {
        ...     
        abstract boolean canInsert(Node n);    
        public String toString() {
            return value;
        }
        ...    
    }

    public static class A extends NodeBase {
        boolean canInsert(Node n) {
            return n instanceof B;
        }
    }
    public static class B extends NodeBase {
        boolean canInsert(Node n) {
            return n instanceof NN || n instanceof C;
        }
    }

    ...

    public static class NN extends NodeBase {
        boolean canInsert(Node n) {
            return false;
        }
    }

创建一个树类:
public class MyTree {

    Node root;
    Node lastInserted = null;

    public void insert(String label) {
        Node n = NodeFactory.create(label);

        if (lastInserted == null) {
            root = n;
            lastInserted = n;
            return;
        }
        Node current = lastInserted;
        while (!current.addChild(n)) {
            current = current.getParent();
            if (current == null) {
                throw new RuntimeException("Impossible to insert " + n);
            }
        }
        lastInserted = n;
    }
    ...
}

然后打印树:


public class MyTree {
    ...
    public static void main(String[] args) {
        List input;
        ...
        MyTree tree = new MyTree();
        for (String line : input) {
            tree.insert(line);
        }
        tree.print();
    }

    public void print() {
        printSubTree(root, "");
    }
    private static void printSubTree(Node root, String offset) {
        Deque  children = root.getChildren();
        Iterator i = children.descendingIterator();
        System.out.println(offset + root);
        while (i.hasNext()) {
            printSubTree(i.next(), offset + " ");
        }
    }
}

感谢您提供的出色答案。很棒的树形解决方案。但是需要对类A、B、C、DD、NN进行大量更改。 - gtiwari333
1
你可以将 A、B、C 类从节点解耦,只留下 canInsert() 方法。或者如果你将插入策略注入到 Tree 类中,甚至可以将它们完全置空。 - Aleksey Otrubennikov

3
一个具有5个状态的Mealy自动机解决方案: 等待A看到A看到B看到C看到DD
解析完全在一个方法中完成。有一个current节点,它是除了NN之外最后一个节点。一个节点有一个父节点,除了根节点。在状态seen (0)中,current节点表示一个(0)(例如,在状态seen C中,current可以是上面示例中的C1)。最棘手的是状态seen DD,它有最多的出边(BCDDNN)。
public final class Parser {
    private final static class Token { /* represents A1 etc. */ }
    public final static class Node implements Iterable<Node> {
        /* One Token + Node children, knows its parent */
    }

    private enum State { ExpectA, SeenA, SeenB, SeenC, SeenDD, }

    public Node parse(String text) {
        return parse(Token.parseStream(text));
    }

    private Node parse(Iterable<Token> tokens) {
        State currentState = State.ExpectA;
        Node current = null, root = null;
        while(there are tokens) {
            Token t = iterator.next();
            switch(currentState) {
                /* do stuff for all states */

                /* example snippet for SeenC */
                case SeenC:
                if(t.Prefix.equals("B")) {
                    current.PN.PN.AddChildNode(new Node(t, current.PN.PN));
                    currentState = State.SeenB;
                } else if(t.Prefix.equals("C")) {

            }
        }
        return root;
    }
}

我对那些向上插入节点的训练有些不满意 (current.PN.PN)。最好使用明确的状态类使私有parse方法更易读。然后,解决方案更接近于@AlekseyOtrubennikov提供的解决方案。也许直截了当地使用LL方法会产生更美观的代码。或者最好将语法重新表述为BNF,并委托解析器创建。


一个简单的LL解析器,一个产生规则:

// "B" ("NN" || C)*
private Node rule_2(TokenStream ts, Node parent) {
    // Literal "B"
    Node B = literal(ts, "B", parent);
    if(B == null) {
        // error
        return null;
    }

    while(true) {
        // check for "NN"
        Node nnLit = literal(ts, "NN", B);
        if(nnLit != null)
            B.AddChildNode(nnLit);

        // check for C
        Node c = rule_3(ts, parent);
        if(c != null)
            B.AddChildNode(c);

        // finished when both rules did not match anything
        if(nnLit == null && c == null)
            break;
    }

    return B;
}

TokenStream 增强了 Iterable<Token>,允许向前查看流 - LL(1),因为解析器必须在字面值 NN 和深入两种情况之间进行选择(rule_2 是其中之一)。看起来很不错,然而这里缺少一些 C# 特性...


嗨,Stefan!LL解析器通常像我回答中的代码一样工作。我的代码使用树结构,而你的使用递归树。 - Aleksey Otrubennikov
是的,canInsert 方法类似于一个令牌/节点的前瞻。在你的解决方案中,生产规则和相应的节点被合并到一个类中。由于节点知道它们的子节点,所以代码也可以处理更复杂的语法。嗯,我想我必须重新实现你的解决方案 :) - Stefan Hanke

3

@Stefan和@Aleksey是正确的:这是一个简单的解析问题。 您可以在扩展Backus-Naur形式中定义您的层次约束:

A  ::= { B }
B  ::= { NN | C }
C  ::= { NN | DD }
DD ::= { NN }

这个描述可以转化为状态机并实现。但是有很多工具可以有效地为您完成这项工作: 解析生成器
我发布我的答案只是为了展示使用Haskell(或其他函数式语言)解决此类问题非常容易。
以下是一个完整的程序,它从stdin读取字符串并将解析树打印到stdout。
-- We are using some standard libraries.
import Control.Applicative ((<$>), (<*>))
import Text.Parsec
import Data.Tree

-- This is EBNF-like description of what to do.
-- You can almost read it like a prose.
yourData = nodeA +>> eof

nodeA  = node "A"  nodeB
nodeB  = node "B" (nodeC  <|> nodeNN)
nodeC  = node "C" (nodeNN <|> nodeDD)
nodeDD = node "DD" nodeNN
nodeNN = (`Node` []) <$> nodeLabel "NN"

node lbl children
  = Node <$> nodeLabel lbl <*> many children

nodeLabel xx = (xx++)
  <$> (string xx >> many digit)
  +>> newline

-- And this is some auxiliary code.
f +>> g = f >>= \x -> g >> return x

main = do
  txt <- getContents
  case parse yourData "" txt of
    Left err  -> print err
    Right res -> putStrLn $ drawTree res

执行该程序并将数据存储在zz.txt中,将会输出下面这个漂亮的树状结构:
$ ./xxx < zz.txt 
A1
+- B1
|  +- NN1
|  +- NN2
|  `- C1
|     +- NN2
|     +- DD1
|     +- DD2
|     |  +- NN3
|     |  `- NN4
|     `- DD3
|        `- NN5
`- B2
   +- NN6
   +- C2
   |  +- DD4
   |  +- DD5
   |  |  +- NN7
   |  |  `- NN8
   |  `- DD6
   |     `- NN9
   `- C3
      +- DD7
      `- DD8

以下是它如何处理格式错误的输入:

$ ./xxx
A1
B2
DD3
(line 3, column 1):
unexpected 'D'
expecting "B" or end of input

2
我猜那是一个面向对象编程的问题。 - Aleksey Otrubennikov
@Aleksey,看来你是对的。parsing标签的存在和缺乏oop让我感到困惑。 - max taldykin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接