《力扣刷题》数据结构(字符串中的第一个唯一字符)

《力扣刷题》数据结构(字符串中的第一个唯一字符),第1张

题目描述

若存在一个字符串 s,要求找到它的第一个不重复的字符,并返回它的索引;如果不存在,则返回 -1

题目来源 C 语言具体代码实现

作者本人想法!!!

#include 
#include 

int firstUniqChar(char *s){
    for(int i = 0; i < strlen(s); i++){
        int j = 0;
        for(; j < strlen(s); j++){
            if(s[i] != s[j] || i == j){
                continue;
            }else{
                break;
            }
        }
        if(j == strlen(s)){
            return i;
        }
    }
    return -1;
}

int main(void){
	int index = firstUniqChar("leetcode");
	printf("%d", index);  // 0
	return 0;
} 

此道题还可以用哈希表来做!!!但是作者能力有限,还未学习哈希表这一块内容,所以先贴部分代码

struct hashTable {
    int key;
    int val;
    UT_hash_handle hh;
};

int firstUniqChar(char* s) {
    struct hashTable* frequency = NULL;
    int n = strlen(s);
    for (int i = 0; i < n; i++) {
        int ikey = s[i];
        struct hashTable* tmp;
        HASH_FIND_INT(frequency, &ikey, tmp);
        if (tmp == NULL) {
            tmp = malloc(sizeof(struct hashTable));
            tmp->key = ikey;
            tmp->val = 1;
            HASH_ADD_INT(frequency, key, tmp);
        } else {
            tmp->val++;
        }
    }
    for (int i = 0; i < n; i++) {
        int ikey = s[i];
        struct hashTable* tmp;
        HASH_FIND_INT(frequency, &ikey, tmp);
        if (tmp != NULL && tmp->val == 1) {
            return i;
        }
    }
    return -1;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/584963.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存