本帖最后由 hjy 于 2020-10-27 02:50 编辑
下面这个是sudo code, 我感觉可以试试这样:
sudo code:[Python] 纯文本查看 复制代码 def dfs(node, str, idx):
initialize a buffer stack
i = idx
while (i < len(str)):
if str[i] is '<':
push i onto stack
i++
else if str[i] is '>':
peek stack top store that as j, tag_name = str[j+1,i]
if the tag_name starts with "/":
pop stack top
peek stack top as k
str [k+1, j] is the value of the current tag
set tag name and value of the current node(don't set the value if current node's child list is not empty)
return node, i+1
else:
if i + 1 < str.length and str[i+1] == '<':
childnode, nextidx = dfs(new node(), str, i+1)
i = nextidx
add childnode to current child list
else:
push i to stack
i ++
else:
i++
return node, i+1
|