387.字符串中的第一个唯一字符Java
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
输入输出样式
示例1:
s = “leetcode”
返回 0
示例2:
s = “loveleetcode”
返回 2
本题来自LeetCode:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
思路
利用HashMap,首先遍历字符串,存储每个字符和它出现的次数。第二遍再遍历字符串,只要在HashMap中存储的次数为1则返回索引即可。
算法分析
时间复杂度O(n),空间复杂度为O(26)
求解函数
public int firstUniqChar(String s) {
HashMap<Character, Integer> hash = new HashMap();
//将每个字符和出现的次数存储到HashMap中
for (int i = 0; i < s.length(); ++i) {
int count = hash.getOrDefault(s.charAt(i), 0) + 1;
hash.put(s.charAt(i), count);
}
for (int i = 0; i < s.length(); ++i) {
//如果出现次数为1则是我们要找的
if (hash.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}