Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

想到一个更好的解法 #166

Open
981377660LMT opened this issue Aug 31, 2021 · 0 comments
Open

想到一个更好的解法 #166

981377660LMT opened this issue Aug 31, 2021 · 0 comments

Comments

@981377660LMT
Copy link

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

class TNode {
  name: string
  children?: TNode[]
  constructor(name: string, children?: TNode[]) {
    this.name = name
    this.children = children
  }
}

// 编写一个算法解析以下符号,转换为json树的结构
const str = `<xml><div><p><a/></p><p></p></div></xml><xml><div><p><a/></p><p></p></div></xml>`

// 解法
const toTree = (str: string) => {
  const root = new TNode('', [])

  const dfs = (str: string, parent: TNode) => {
    const regexp = /<(.*?)>(.*?)<\/\1>/g
    const match = [...str.matchAll(regexp)]

    if (match.length) {
      for (const group of match) {
        const name = group[1]
        const childStr = group[2]
        const root = new TNode(name, [])
        parent.children!.push(root)
        dfs(childStr, root)
      }
    } else {
      parent.children!.push(new TNode(str))
    }
  }
  dfs(str, root)

  return root.children
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant