题目链接: 字符串中的第一个唯一字符
有关题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。
如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
题解
法一:哈希表存储频数
参考官方题解
struct hashTable {
int key;
int val;
UT_hash_handle hh;//内部使用的哈希句柄
};
int firstUniqChar(char * s){
struct hashTable* freq = NULL;//存储频数
for (int i = 0; i < strlen(s); i++)
{
int ikey = s[i];
struct hashTable* temp;
HASH_FIND_INT(freq, &ikey, temp);
if (NULL == temp)
{
temp = (struct hashTable*)malloc(sizeof(struct hashTable));
temp->key = ikey, temp->val = 1;
HASH_ADD_INT(freq, key, temp);
}
else
{
temp->val++;
}
}
for (int i = 0; i < strlen(s); i++)
{
int x = s[i];
struct hashTable* temp;
HASH_FIND_INT(freq, &x, temp);
if (temp != NULL && (temp->val == 1))
{
return i;
}
}
return -1;
}
法二:用哈希表存储索引
参考官方题解
struct hashTable {
int key;
int val;
UT_hash_handle hh;
};
int firstUniqChar(char * s){
struct hashTable* freq = NULL;
int n = strlen(s);
for (int i = 0; i < n; i++)
{
int ikey = s[i];
struct hashTable* temp;
HASH_FIND_INT(freq, &ikey, temp);
if (NULL == temp)
{
temp = (struct hashTable*)malloc(sizeof(struct hashTable));
temp->key = ikey, temp->val = i;
HASH_ADD_INT(freq, key, temp);
}
else
{
temp->val = -1;
}
}
int first = n;
struct hashTable *iter, *temp;
HASH_ITER(hh, freq, iter, temp){
int pos = iter->val;
if (pos != -1 && pos < first)
{
first = pos;
}
}
if (first == n)
return -1;
return first;
}