题目来源于力扣–https://leetcode-cn.com/
可以用一个临时的数组来对出现的字符进行计数,题目要求,字符全都是小写的,所以我们可以给定一个26大小的数组来存放每个字符出现的次数,最后循环判断哪个地方的字符为1,就是第一个出现的唯一字符,否则返回-1。
main函数代码
#include<stdio.h>
int firstUniqChar(char * s);
int main(){
char s[]="leetcode";
int num = firstUniqChar(s);
printf("%d",num);
return 0;
}
计数代码
int firstUniqChar(char * s){
int count[26]={};
int i = 0;
// 数组不为空,就继续进行
while(s[i]){
// 这个地方是,26个小写字母从a开始,字母进行a-a=0,b-a=1,,,,,,,,依次类推,z-a=25,
// 计算每个字符出现的次数,存储下来。
count[s[i]-'a']++;
i++;
}
// 遍历数组,因为字符是乱序的,要保证第一个唯一,所以不能从0开始遍历count数组,要通过
// 原字符出现的顺序进行遍历。
for(int j=0;j<i;j++){
if(count[s[j]-'a']==1){
return j;
}
}
return -1;
}