这道题来自HackerRank,难度为medium,记录一下解题过程。(不得不承认我菜,竟然被一道medium难度的题难住)

原题面如下:

We have defined our own markup language HRML. In HRML, each element consists of a starting and ending tag, and there are attributes associated with each tag. Only starting tags can have attributes. We can call an attribute by referencing the tag, followed by a tilde, '~' and the name of the attribute. The tags may also be nested.

The opening tags follow the format:

<tag-name attribute1-name = "value1" attribute2-name = "value2" ...>

The closing tags follow the format:

</tag-name>

For example:

<tag1 value = "HelloWorld">
<tag2 name = "Name1">
</tag2>
</tag1>

The attributes are referenced as:

tag1~value  
tag1.tag2~name

You are given the source code in HRML format consisting of  lines. You have to answer  queries. Each query asks you to print the value of the attribute specified. Print "Not Found!" if there isn't any such attribute.

Input Format

The first line consists of two space separated integers,  and  specifies the number of lines in the HRML source program.  specifies the number of queries.

The following  lines consist of either an opening tag with zero or more attributes or a closing tag.There is a space after the tag-name, attribute-name, '=' and value.There is no space after the last value. If there are no attributes there is no space after tag name.

 queries follow. Each query consists of string that references an attribute in the source program.More formally, each query is of the form ~ where  and  are valid tags in the input.

Constraints

  • 1≤N≤20
  • 1≤Q≤20
  • Each line in the source program contains, at max,  characters.
  • Every reference to the attributes in the  queries contains at max  characters.
  • All tag names are unique and the HRML source program is logically correct.
  • A tag can have no attributes as well.

Output Format

Print the value of the attribute for each query. Print "Not Found!" without quotes if there is no such attribute in the source program.

Sample Input

4 3
<tag1 value = "HelloWorld">
<tag2 name = "Name1">
</tag2>
</tag1>
tag1.tag2~name
tag1~name
tag1~value

Sample Output

Name1
Not Found!
HelloWorld

我的大体思路,分3步:
1.文本解析
2.1.标签放入N叉树,属性放入map集合;“每个树节点”
再用map映射到一个“属性集合”;(注意这里有两类map,一类是map1<标签节点,属性清单>,一类是map2<属性名,属性值>
2.2.由于根节点可能不止一个,所以应该用森林
3.树的查找。用层序遍历找到后,通过map1映射出属性清单;再通过map2用属性名映射出属性值;

好了,开始吧:
1.文本解析
这种在线答题的模式有个优点就是,你不能使用开源库,啥都得自己动手。这对基础弱的新手,其实是很好的锻炼。
比如这种号称HRML的文本解析,要是随便拿个现成的解析器,这题就完成三分之一了。

这里的文本解析一共有2部分,第一是HRML解析,第二是query语句的解析。

/*代码后面补上*/

2.把解析得到的数据装进N叉树结构

3.根据题面中query的路径,去树结构中找到对应路径,并输出结果