力扣387-字符串中的第一个唯一字符
一、原题题目
1.1 题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0s = “loveleetcode”
返回 2
提示:你可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
二、解题思路
2.1 题目意思理解
这是一道简单的字符串相关题目,根据题目意思,要找出只出现一次的并且最靠前的那一个,我们可以用一个哈希表来存储出现的字符和出现的次数,再依次用字符串中的字符去取哈希表中的个数,值为1就返回该字符在字符串中的位置。
2.2 详细代码(Java)
public class Solution {
public static int firstUniqChar(String s) {
char[] ch = s.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
map.put(ch[i], map.getOrDefault(ch[i], 0) + 1);
}
for(int i = 0; i < s.length(); i++) {
if(map.get(ch[i]) <= 1) return i;
}
return -1;
}
}
2.3 算法执行结果

效率好像不是很高。当我直接用数组存储每个字符的个数时,代码如下,性能得到了提升。
public class Solution {
public static int firstUniqChar(String s) {
char[] ch = s.toCharArray();
int[] count = new int[26];
for(int i = 0; i < s.length(); i++) {
count[ch[i]-'a']++;
}
for(int i = 0; i < s.length(); i++) {
if(count[ch[i]-'a']==1) return i;
}
return -1;
}
}
