387. First Unique Character in a String
Description
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples: s = "leetcode" return 0. s = "loveleetcode", return 2.
Solution
- 題意即返回一個字符數組中第一個不重複(就是說在整個字符串中,該字母只出現一次)字母的下標,不存在則返回-1.
- 我的做法是先將該字符串存入一個哈希表中(由於只有26個字符,可以直接用線性哈希表)(同時記錄字符數),然後按照下標從小到大查詢,如果有隻出現一次的字符,那麼返回該字符對應的下標,否則結尾返回-1,代碼如下:
int firstUniqChar(char* s) {
int hash_alpha[26];
memset(hash_alpha,0,sizeof(hash_alpha));
int len = strlen(s);
for (int i = 0;i < len;i++) {
hash_alpha[s[i] - 'a']++;
}
for (int i = 0;i < len;i++) {
if (hash_alpha[s[i] - 'a'] == 1)
return i;
}
return -1;
}