題目:字符串中的第一個唯一字符
給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
注意事項:您可以假定該字符串只包含小寫字母。
C語言解題
int firstUniqChar(char* s) {
int len = strlen(s);
int ch[26] = { 0 };
for (int i = 0; i < len; i++) {
ch[s[i] - 'a']++;
}
for (int i = 0; i < len; i++) {
if (ch[s[i] - 'a'] == 1)
return i;
}
return -1;
}
用一個數組記錄出現的字符的個數,再遍歷這個數組。