Skip to content

想到一个更好的解法 #166

Description

@981377660LMT

原题 : 编写一个算法解析以下符号,转换为json树的结构

classTNode{name: stringchildren?: TNode[]constructor(name: string,children?: TNode[]){this.name=namethis.children=children}}// 编写一个算法解析以下符号,转换为json树的结构conststr=`<xml><div><p><a/></p><p></p></div></xml><xml><div><p><a/></p><p></p></div></xml>`// 解法consttoTree=(str: string)=>{constroot=newTNode('',[])constdfs=(str: string,parent: TNode)=>{constregexp=/<(.*?)>(.*?)<\/\1>/gconstmatch=[...str.matchAll(regexp)]if(match.length){for(constgroupofmatch){constname=group[1]constchildStr=group[2]constroot=newTNode(name,[])parent.children!.push(root)dfs(childStr,root)}}else{parent.children!.push(newTNode(str))}}dfs(str,root)returnroot.children}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions