1941. 检查是否所有字符出现次数相同Java
文章发布较早,内容可能过时,阅读注意甄别。
# 题目
给你一个字符串 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 只包含小写英文字母。
# 思路
HashMap
# 解法
class Solution {
public boolean areOccurrencesEqual(String s) {
Map<Character,Integer> map=new HashMap<>();
Set<Integer> set=new HashSet<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
map.put(c,map.getOrDefault(c,0)+1);
}
for(char c:map.keySet()){
set.add(map.get(c));
}
if(set.size()>1) return false;
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 总结
- 分析出几种情况,然后分别对各个情况实现