---
title: 'LeetCode 387. First Unique Character in a String'
disqus: hackmd
---
# LeetCode 387. First Unique Character in a String
## Description
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
## Example
Input: s = "leetcode"
Output: 0
Input: s = "loveleetcode"
Output: 2
## Constraints
1 <= s.length <= 10^5^
s consists of only lowercase English letters.
## Answer
此題可用hash table的概念來將26個英文當成index而存的值就是所計算的數量,當第一個檢查到是1的值時,其index即為答案。
```Cin=
//2021_11_17
int firstUniqChar(char * s) {
int i = 0, len = strlen(s);
int *cnt = (int *)malloc(sizeof(int)*26);
for(i = 0; i< 26; i++){ cnt[i] = 0; }
for(i = 0; i < len; i++){
cnt[s[i] - 'a']++;
}
for(i = 0; i < len; i++){
if(cnt[ s[i] - 'a' ] == 1){
free(cnt);
return i;
}
}
free(cnt);
return -1;
}
```
## Link
https://leetcode.com/problems/first-unique-character-in-a-string/
###### tags: `Leetcode`