1941. 检查是否所有字符出现次数相同
1941. 检查是否所有字符出现次数相同
题目
Given a string s, return true ifs is a good string, or falseotherwise.
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 <= 1000sconsists 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 <= 1000s只包含小写英文字母。
解题思路
字符频率统计:
- 创建一个长度为 26 的数组
freq,初始值为 0,用于记录每个字母的出现次数。数组下标与字母对应关系为char.charCodeAt() - 97。 - 遍历字符串
s,更新freq数组。
- 创建一个长度为 26 的数组
验证频率一致性:
- 使用
Set数据结构去重,将freq中的非零值添加到Set中。 - 如果
Set的大小为 1,则说明所有字符的出现次数相等;否则不相等。
- 使用
复杂度分析
时间复杂度:
O(n)- 遍历字符串
s计算频率:O(n),其中n是字符串长度。 - 构建
Set:O(26),常数时间。 - 总时间复杂度:
O(n)。
- 遍历字符串
空间复杂度:
O(1)- 频率数组
freq:O(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 | 使字符串中不同字符的数目相等 | 哈希表 字符串 计数 | 🟠 | 🀄️ 🔗 |
