1.题目要求:
给你一个字符串 word。如果 word 中同时出现某个字母 c 的小写形式和大写形式,并且 每个 小写形式的 c 都出现在第一个大写形式的 c 之前,则称字母 c 是一个 特殊字母 。
返回 word 中 特殊字母 的数量。
示例 1:
输入:word = "aaAbcBC"
输出:3
解释:
特殊字母是 'a'、'b' 和 'c'。
示例 2:
输入:word = "abc"
输出:0
解释:
word 中不存在特殊字母。
示例 3:
输入:word = "AbBCab"
输出:0
解释:
word 中不存在特殊字母。
2.做题思路:
采用哈希表,使用哈希函数解题
3.解题代码:
int numberOfSpecialChars(char* word) {
int* big = (int*)malloc(sizeof(int) * 26);//此数组存大写字母的下标
memset(big,-1,sizeof(int) * 26);
int* small = (int*)malloc(sizeof(int) * 26);//此数组存小写字母的下标
memset(small,-1,sizeof(int) * 26);
int i = 0;
for(i = 0;i < strlen(word);i++){
if(word[i] >= 'A'&&word[i] <= 'Z'){
int hashindex = word[i] - 'A';//设置哈希函数
big[hashindex] = i;
}
}
for(i = 0;i < strlen(word);i++){
if(word[i] >= 'a'&&word[i] <= 'z'){
int hashindex = word[i] - 'a';//设置哈希函数
small[hashindex] = i;
}
}
int count = 0;
for(i = 0;i < 26;i++){
if(big[i] != -1&&small[i] != -1){
count++;//做判断
}
}
return count;
}