leetcode练习——(题目序号387)

字符串中的第一个唯一字符。
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle

解题思路:设置一个数组a[26],因为一共只有26个小写字母,每个字母和‘a’的ASCII码差值在26以内,数组用来存放每个字母出现的次数;第一次遍历存数,第二次遍历找出第一个惟一的字符。

int firstUniqChar(char * s){
    
    
    int a[27]={
    
    0};
    for(int i=0;i<strlen(s);i++){
    
    
        a[s[i]-'a']++;
    }
    for(int i=0;i<strlen(s);i++){
    
    
        if(a[s[i]-'a']==1) return i;
    }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/lthahaha/article/details/105501320