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

如何用对象判断str2能否由str1组成?计数为负时返回false的问题

问题解决:判断str2是否可由str1字符组成

你的核心问题是未检查字符剩余计数是否足够,同时代码还存在全局变量污染的隐患,以下是修复方案:

原代码的两个关键问题

  1. char是全局变量,多次调用函数会残留之前的计数结果,导致后续判断出错。
  2. 第二个循环仅判断字符是否存在,未校验剩余可用数量,导致字符超用时计数变负仍返回true。

修复后的代码

function charCount(str1, str2) {
  // 将字符统计对象移至函数内部,避免全局污染
  const char = {};
  str1 = str1.toLowerCase();
  str2 = str2.toLowerCase();

  // 统计str1中每个字符的出现次数
  for (let i = 0; i < str1.length; i++) {
    const currentChar = str1[i];
    char[currentChar] = (char[currentChar] || 0) + 1;
  }

  // 校验str2的字符是否都能从str1中获取足够数量
  for (let i = 0; i < str2.length; i++) {
    const currentChar = str2[i];
    // 字符不存在 或 剩余数量已为0,直接返回false
    if (!char[currentChar] || char[currentChar] === 0) {
      return false;
    }
    // 剩余数量减1
    char[currentChar]--;
  }

  return true;
}

// 测试用例
console.log(charCount("hello", "helllo")); // 输出 false
console.log(charCount("hello", "hello"));  // 输出 true
console.log(charCount("abc", "abcd"));     // 输出 false

关键修改说明

  • 全局变量本地化:把char放到函数内部,每次调用函数都会重新初始化,彻底避免旧数据干扰。
  • 循环变量声明:给循环变量i加上let,防止其变成全局变量引发意外问题。
  • 计数校验逻辑:在处理str2的字符时,先检查该字符的剩余可用数量:
    • 如果字符不在统计对象中,直接返回false
    • 如果剩余数量已经为0,说明str1的该字符已用完,无法满足str2需求,立即返回false
  • 简化计数逻辑:用char[currentChar] = (char[currentChar] || 0) + 1替代原有的if-else,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:41