Q32-code71- 简化路径 + Q33-code341- 扁平化嵌套列表迭代器

67 阅读2分钟

Q32- code71- 简化路径

实现思路

1 方法1: 栈

  • 难点是要想到通过/来split路径字符,通过考虑到分割后一共有几种情况
  • 易错点1: 空字符(多个/相邻) 和 当个. 都是无意义非法字符,需要略过
  • 易错点2: 需要通过"/"开头,再拼接后面的合法内容

参考文档

01-直接参考实现

代码实现

1 方法1: 栈 时间复杂度: O(n); 空间复杂度(n)

function simplifyPath(path: string): string {
  // paths的成员类型可能有5种情况:字符数字/空字符/.././ ...
  let paths = path.split("/");
  let ans = [];
  for (const part of paths) {
    if (part === "..") ans.pop();
    // 易错点1: 空字符(多个/相邻) 和 当个. 都是无意义非法字符,需要略过
    else if (part === "" || part === ".") continue;
    else ans.push(part);
  }
  // 易错点2: 需要通过"/"开头,再拼接后面的合法内容
  return "/" + ans.join("/");
}

Q33- code341- 扁平化嵌套列表迭代器

实现思路

1 方法1: 队列 + NestedInteger特性的API

  • 注意hasNext: 要通过while来递归入队成员,直到一个成员是数字时 才中止
  • 需要明确,由于调用next时 每次都会先调用hasNext,所以运行next时,队首一定是 Integer

参考文档

01- 方法1参考实现

02- 生成器方法参考实现

代码实现

1 队列 + NestedInteger特性的API 时间复杂度: 均摊O(1); 空间复杂度(n)

class NestedIterator {
  st: NestedInteger[];
  constructor(nestedList: NestedInteger[]) {
    this.st = nestedList;
  }

  hasNext(): boolean {
    // 易错点1:要通过while来递归入队成员,直到一个成员是数字时 才中止
    while (this.st.length) {
      const cur = this.st[0];
      if (cur.isInteger()) return true;
      else {
        this.st.shift();
        this.st.unshift(...cur.getList());
      }
    }
    return false;
  }

  // 根据题意
  // 由于调用next时 每次都会先调用hasNext,所以运行next时,队首一定是 Integer
  next(): number {
    return this.st.shift().getInteger();
  }
}

2 方法2: 生成器函数 + 递归调用法

class NestedIterator {
	constructor(nestedList: NestedInteger[]) {
		// 通过生成器函数 递归遍历嵌套数组
		const gen = function *(arr) {
			for (let nest of arr) {
				if (nest.isInteger()) {
					yield nest.getInteger()
				} else {
					yield *gen(nest.getList())
				}
			}
		}
		this.iter = gen(nestedList)
		//调用迭代器的next方法,返回 {value: val, done: true/false}
    this.curInfo = this.iter.next()
  }

  hasNext(): boolean {
		return !this.curInfo.done
  }

  next(): number {
		const ret = this.curInfo.value
		this.curInfo = this.iter.next()
		return ret
  }
}