JavaScript / TypeScript for LeetCode (157)

这篇博客介绍了如何使用JavaScript和TypeScript解决LeetCode的第1002题——查找常用字符。作者分享了其解题思路,并提供了详细的JavaScript和TypeScript解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.6.27
  • 结束时间:undefined

GitHub仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

1、题目要求

( LeetCode – 第1002题 ) 查找常用字符

2、解题思路

1、统计第一个字符串的字符出现次数,之后用于更新为最小的出现次数
2、统计字符串数组中每个字符串的字符出现次数
    2.1、遍历tempCount,把tempCount里统计的字频里的较小的值更新到minCount中
3、遍历minCount,统计结束后,把字频数组代表的字符转成字符,保存到结果数组
4、返回结果数组

2.1、JavaScript Solution

/**
 * @param {string[]} A
 * @return {string[]}
 */
var commonChars = function (A) {
  const res = [];
  if (A.length === 0) {
    return res;
  }
  // 1、统计第一个字符串的字符出现次数,之后用于更新为最小的出现次数
  const minCount = countChar(A[0]);

  //2、统计字符串数组中每个字符串的字符出现次数
  for (let i = 1; i < A.length; i++) {
    let tempCount = countChar(A[i]);

    // 2.1、遍历tempCount,把tempCount里统计的字频里的较小的值更新到minCount中
    for (let j = 0; j < tempCount.length; j++) {
      if (tempCount[j] < minCount[j]) {
        minCount[j] = tempCount[j];
      }
    }
  }

  //3、遍历minCount,统计结束后,把字频数组代表的字符转成字符,保存到结果数组
  for (let i = 0; i < minCount.length; i++) {
    let commonChar = String.fromCharCode(97 + i);

    //如果最小出现次数大于0,就出现几次加几次进结果数组
    while (minCount[i]-- > 0) {
      res.push(commonChar);
    }
  }

  //4、返回结果数组
  return res;
};

//统计字符串中字符出现次数
function countChar(s) {
  let arr = new Array(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    arr[s.charCodeAt(i) - 97]++;
  }

  return arr;
}

2.2、TypeScript Solution

function commonChars(A: string[]): string[] {
    const res: string[] = [];
    if (A.length === 0) {
      return res;
    }
    // 1、统计第一个字符串的字符出现次数,之后用于更新为最小的出现次数
    const minCount: number[] = countChar(A[0]);
  
    //2、统计字符串数组中每个字符串的字符出现次数
    for (let i: number = 1; i < A.length; i++) {
      let tempCount: number[] = countChar(A[i]);
  
      // 2.1、遍历tempCount,把tempCount里统计的字频里的较小的值更新到minCount中
      for (let j: number = 0; j < tempCount.length; j++) {
        if (tempCount[j] < minCount[j]) {
          minCount[j] = tempCount[j];
        }
      }
    }
  
    //3、遍历minCount,统计结束后,把字频数组代表的字符转成字符,保存到结果数组
    for (let i: number = 0; i < minCount.length; i++) {
      let commonChar: string = String.fromCharCode(97 + i);
  
      //如果最小出现次数大于0,就出现几次加几次进结果数组
      while (minCount[i]-- > 0) {
        res.push(commonChar);
      }
    }
  
    //4、返回结果数组
    return res;
  
 
  
};

 //统计字符串中字符出现次数
 function countChar(s: string): number[] {
    let arr: number[] = new Array(26).fill(0);
    for (let i: number = 0; i < s.length; i++) {
      arr[s.charCodeAt(i) - 97]++;
    }
  
    return arr;
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值