题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
注意事项:您可以假定该字符串只包含小写字母
题解思路
- 暴力法: 时间复杂度 O(n²),空间复杂度 O(1)
- 哈希表: 时间复杂度 O(n),空间复杂度 O(1),使用哈希表遍历一次记录字符出现次数
AC代码
暴力解法:
int firstUniqChar(char * s){
int i, j;
for(i = 0; s[i] != '\0'; i++) {
for(j = 0; s[j] != '\0'; j++) {
if(s[i] == s[j] && i != j) {
break;
}
}
if(s[j] == '\0') {
return i;
}
}
return -1;
}
Accepted
104/104 cases passed (32 ms)
Your runtime beats 30.35 % of c submissions
Your memory usage beats 95.22 % of c submissions (8.2 MB)
哈希表解法:
int firstUniqChar(char * s){
int hashtab[26] = {0};
int i = 0;
while(s[i] != '\0') {
hashtab[s[i] - 'a']++;
i++;
}
i = 0;
while(s[i] != '\0') {
if(hashtab[s[i] - 'a'] == 1) {
return i;
}
i++;
}
return -1;
}
Accepted
104/104 cases passed (8 ms)
Your runtime beats 98.72 % of c submissions
Your memory usage beats 28.1 % of c submissions (8.3 MB)