You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将表示哈希深度的整数数组转为哈希及构建嵌套结构技术问询

嘿,我来帮你搞定这个带深度标记的扁平化数组转换问题!你需要完成两个核心任务:转成哈希结构,以及转成支持递归构建的嵌套列表结构对吧?我给你一步步拆解,附上实用的代码示例。

一、将带深度的扁平化数组转换为哈希结构

核心思路是用栈结构跟踪当前层级的哈希节点:遍历数组时,根据当前元素的深度调整栈的长度,找到对应的父哈希节点,然后把当前元素作为子节点添加进去。这样能高效处理嵌套层级,不管深度跳变都能适配。

举个JavaScript的实现例子(你可以根据自己用的语言调整逻辑):

function flatToHash(flatArray) {
  const rootHash = {};
  // 栈里存的是{深度, 当前哈希节点},初始根节点深度设为-1,确保第一个深度0的元素能找到父节点
  const stack = [{ depth: -1, node: rootHash }];

  for (const [key, depth] of flatArray) {
    // 弹出栈中深度大于等于当前深度的节点,找到当前节点的父节点
    while (stack[stack.length - 1].depth >= depth) {
      stack.pop();
    }
    const parentNode = stack[stack.length - 1].node;
    // 给父节点添加当前子哈希(如果key重复可以改成数组存多个值,这里假设key唯一)
    parentNode[key] = {};
    // 把当前节点推入栈,供后续子节点使用
    stack.push({ depth, node: parentNode[key] });
  }

  return rootHash;
}

// 测试示例
const testArray = [["A", 0], ["B", 1], ["C", 2], ["D", 1], ["E", 0]];
console.log(flatToHash(testArray));
// 输出结果:{ A: { B: { C: {} }, D: {} }, E: {} }
二、转换为嵌套列表结构(支持有序/无序)

同样用栈来跟踪当前层级的列表容器,遍历过程中根据深度找到父列表项,把当前元素作为列表项添加,同时为当前项创建子列表容器(如果后续有更深层级的元素)。这样生成的嵌套结构可以直接用来递归渲染成HTML的<ul>/<ol>,或者其他格式的列表。

还是用JavaScript实现,生成JSON格式的嵌套结构(方便后续渲染):

function flatToNestedList(flatArray, isOrdered = false) {
  const listType = isOrdered ? "ol" : "ul";
  // 根容器是最外层的列表
  const rootList = { type: listType, children: [] };
  const stack = [{ depth: -1, node: rootList }];

  for (const [text, depth] of flatArray) {
    // 调整栈到当前深度的父容器
    while (stack[stack.length - 1].depth >= depth) {
      stack.pop();
    }
    const parentContainer = stack[stack.length - 1].node;

    // 创建当前列表项,包含文本和子列表容器
    const listItem = { type: "li", text: text, children: [] };
    parentContainer.children.push(listItem);

    // 把当前项的子列表容器推入栈,供后续更深层级的元素使用
    stack.push({ depth, node: { type: listType, children: listItem.children } });
  }

  return rootList;
}

// 测试无序列表
const testArray = [["Item 1", 0], ["Subitem 1-1", 1], ["Subsubitem 1-1-1", 2], ["Item 2", 0]];
console.log(JSON.stringify(flatToNestedList(testArray), null, 2));
// 输出的结构可以直接渲染成嵌套<ul>

// 测试有序列表
console.log(JSON.stringify(flatToNestedList(testArray, true), null, 2));

如果需要直接生成HTML字符串,只需要修改一下代码,把节点对象换成字符串拼接即可,比如在创建列表项时直接生成<li>text</li>,子列表则递归拼接。

内容的提问来源于stack exchange,提问作者user3229073

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:33:44