Skip to content

Latest commit

 

History

History
132 lines (96 loc) · 4.2 KB

1941.md

File metadata and controls

132 lines (96 loc) · 4.2 KB
title description keywords
1941. 检查是否所有字符出现次数相同
LeetCode 1941. 检查是否所有字符出现次数相同题解,Check if All Characters Have Equal Number of Occurrences,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
1941. 检查是否所有字符出现次数相同
检查是否所有字符出现次数相同
Check if All Characters Have Equal Number of Occurrences
解题思路
哈希表
字符串
计数

1941. 检查是否所有字符出现次数相同

🟢 Easy  🔖  哈希表 字符串 计数  🔗 力扣 LeetCode

题目

Given a string s, return true ifs is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:

Input: s = "abacbc"

Output: true

Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Example 2:

Input: s = "aaabb"

Output: false

Explanation: The characters that appear in s are 'a' and 'b'.

'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

题目大意

给你一个字符串 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 只包含小写英文字母。

解题思路

  1. 字符频率统计

    • 创建一个长度为 26 的数组 freq,初始值为 0,用于记录每个字母的出现次数。数组下标与字母对应关系为 char.charCodeAt() - 97
    • 遍历字符串 s,更新 freq 数组。
  2. 验证频率一致性

    • 使用 Set 数据结构去重,将 freq 中的非零值添加到 Set 中。
    • 如果 Set 的大小为 1,则说明所有字符的出现次数相等;否则不相等。

复杂度分析

  • 时间复杂度O(n)

    • 遍历字符串 s 计算频率:O(n),其中 n 是字符串长度。
    • 构建 SetO(26),常数时间。
    • 总时间复杂度:O(n)
  • 空间复杂度O(1)

    • 频率数组 freqO(26),常数空间。
    • Set 存储不同的频率值:最多 O(26),常数空间。
    • 总空间复杂度:O(1)

代码

/**
 * @param {string} s
 * @return {boolean}
 */
var areOccurrencesEqual = function (s) {
	let freq = new Array(26).fill(0);

	for (let char of s) {
		freq[char.charCodeAt() - 97]++;
	}

	let set = new Set(freq);
	// 删除未出现字母的计数
	set.delete(0);

	return set.size == 1;
};

相关题目

题号 标题 题解 标签 难度 力扣
2103 环和杆 [✓] 哈希表 字符串 🟢 🀄️ 🔗
2531 使字符串中不同字符的数目相等 哈希表 字符串 计数 🟠 🀄️ 🔗