题目描述
给你一个字符串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 只包含小写英文字母。
代码实现
bool areOccurrencesEqual(char * s){
//用于存储字符串各个小写字母出现次数,0表示没有出现该元素
//0~25表示a~z
int num[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0};
int i,loc,temp,flag=1;
char *str = "abcdefghijklmnopqrstuvwxyz";
while(*s!='\0'){ //遍历字符串,统计字符串各个小写字母出现次数
loc=strchr(str,*s)-str;
num[loc]++;
s++;
}
for(i=0;i<26;i++){
if(num[i]!=0){
temp=num[i];
for(int j=i+1;j<26;j++){ //在temp值往后查找
if(num[j]!=0&&temp!=num[j]){ //如果出现数值不同的则说明存在字母出现次数不相同
flag=0;
break; //结束循环
}
}
}
}
if(flag==1){
return true;
}else{
return false;
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-all-characters-have-equal-number-of-occurrences