【Leetcode 1941 】 检查是否所有字符出现次数相同 —— 数组模拟哈希表

58 阅读1分钟

给你一个字符串 s ,如果 s 是一个  字符串,请你返回 true ,否则请返回 false 。

如果 s 中出现过的 所有 字符的出现次数 相同 ,那么我们称字符串 s 是  字符串。

示例 1:

输入: s = "abacbc"
输出: true
解释: s 中出现过的字符为 'a''b''c' 。s 中所有字符均出现 2 次。

示例 2:

输入: s = "aaabb"
输出: false
解释: s 中出现过的字符为 'a''b''a' 出现了 3 次,'b' 出现了 2 次,两者出现次数不同。

提示:

  • 1 <= s.length <= 1000
  • s 只包含小写英文字母。

 

哈希表

/*
https://leetcode.cn/u/cshappyeveryday/
执行用时:62 ms, 在所有 Typescript 提交中击败了100.00%的用户
内存消耗:52.18 MB, 在所有 Typescript 提交中击败了66.67%的用户
2024年8月24日 
*/
function areOccurrencesEqual(s: string): boolean {
  const charMap = new Map<string, number>();
  for (const char of s) {
    charMap.set(char, (charMap.get(char) || 0) + 1);
  }
  return new Set(charMap.values()).size === 1;
}

数组模拟哈希表

// 数组模拟哈希表
function areOccurrencesEqual2(s: string): boolean {
  const arr = new Array(26).fill(0);
  for (const char of s) {
    arr[char.charCodeAt(0) - "a".charCodeAt(0)]++;
  }
  return new Set(arr.filter((n) => n)).size === 1;
}