C语言通过模拟哈希表字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string

这道题最优的解法就是线性复杂度了,为了保证每个元素是唯一的,至少得把每个字符都遍历一遍。

算法的思路就是遍历一遍字符串,然后把字符串中每个字符出现的次数保存在一个散列表中。这个过程的时间复杂度为 O(N)O(N),其中 NN 为字符串的长度。

接下来需要再遍历一次字符串,这一次利用散列表来检查遍历的每个字符是不是唯一的。如果当前字符唯一,直接返回当前下标就可以了。第二次遍历的时间复杂度也是 O(N)O(N)。

#include <stdio.h>
#include <stdlib.h>
int firstUniqChar(char * s);
int main()
{
    int dex;
    char * str = (char *)malloc(sizeof(char)*1000);
    gets(str);
    dex =firstUniqChar(str);
    printf("%d",dex);
}

int firstUniqChar(char * s)
{
    int i,j,len,dex;
    len =strlen(s);
    if(len==0) return -1;
    if(len==1) return 0;
    int nums[26]={0};
    for(i=0;i<len;i++)
    {
        dex =s[i]-'a';
        ++nums[dex];
    }
    //遍历找出个数为1的第一个字符
    for(i=0;i<len;i++)
    {
        dex=s[i]-'a';
        if(nums[dex]==1)
        return i  ;
    }
    return -1 ;
    
}

猜你喜欢

转载自www.cnblogs.com/cocobear9/p/12670429.html
今日推荐