栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

解析Java中的缩进文本树

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解析Java中的缩进文本树

我也添加了一个父指针。也许不用它也可以解析文本,但是父指针使它更容易。首先,您需要具有更多的构造函数:

static final int root_depth = 4; // assuming 4 whitespaces precede the tree rootpublic Section(String text, int depth) {    this.text     = text;    this.depth    = depth;    this.children = new ArrayList<Section>();    this.parent   = null;}public Section(String text, int depth, Section parent) {    this.text     = text;    this.depth    = depth;    this.children = new ArrayList<Section>();    this.parent   = parent;}

然后,当您开始解析文件时,请逐行读取它:

Section prev = null;for (String line; (line = bufferedReader.readLine()) != null; ) {    if (prev == null && line begins with root_depth whitespaces) {        Section root = new Section(text_of_line, root_depth);        prev = root;    }    else {        int t_depth = no. of whitespaces at the beginning of this line;        if (t_depth > prev.getDepth()) // assuming that empty sections are not allowed Section t_section = new Section(text_of_line, t_depth, prev); prev.addChild(t_section);        }        else if (t_depth == prev.getDepth) { Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section);        }        else { while (t_depth < prev.getDepth()) {     prev = prev.getParent(); } // at this point, (t_depth == prev.getDepth()) = true Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section);        }    }}

我已经掩盖了伪代码的一些细节,但我认为您已经获得了如何进行此解析的总体思路。请记住要实现addChild(),getDepth(),getParent()等方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号