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

TypeScript栈中获取最长字符串长度函数返回0求助

排查TypeScript栈最长字符串长度函数的问题

你的代码主要有三个核心问题,导致返回值始终为0:

  • 错误访问类而非实例的属性
    maxLength里用ConstantTimeStack.length获取的是类本身的length属性(默认值为0),而非当前实例中存储元素的数组长度;ConstantTimeStack[i]也是在访问类的静态索引,不是实例里的数组元素,正确应该用实例的this.string(建议改名避免歧义)来操作。

  • 循环逻辑完全倒置
    原代码的if-else逻辑完全搞反:当当前字符串长度temp大于等于newSize时,应该更新最大值变量,而非把temp赋值为newSize;else分支的赋值逻辑毫无意义,导致maxSize始终停留在初始值0。

  • 未处理空栈边界情况
    如果栈是空的(this.string为null),直接遍历会触发报错,需要提前判断。

修正后的代码

class ConstantTimeStack {
  // 改名stackItems,避免和string类型混淆,语义更清晰
  public stackItems: string[] | null;

  constructor() {
    this.stackItems = null;
  }

  public push(item: string): void {
    if (!this.stackItems) {
      this.stackItems = [item];
    } else {
      this.stackItems.push(item);
    }
  }

  public maxLength(): number {
    // 空栈直接返回0
    if (!this.stackItems) return 0;
    
    let maxSize = 0;
    // 遍历实例的数组元素,而非类本身
    for (const item of this.stackItems) {
      const currentLength = item.length;
      if (currentLength > maxSize) {
        maxSize = currentLength;
      }
    }
    return maxSize;
  }
}

let stack = new ConstantTimeStack();
stack.push("Iron");
stack.push("Man");
stack.push("is");
stack.push("the");
stack.push("man");
console.log(stack.maxLength()); // 输出4(对应"Iron"的长度)

关键修改说明

  1. 属性改名:将string改为stackItems,避免类型语义混淆。
  2. 空栈判断:提前处理空栈场景,避免报错。
  3. 遍历逻辑:使用for...of遍历实例的数组元素,简化代码。
  4. 最大值更新:每次比较当前元素长度与maxSize,更大则更新maxSize,逻辑正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:05:22