387、 字符串中的第一个唯一字符
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = “leetcode”
输出: 0
示例 2:
输入: s = “loveleetcode”
输出: 2
示例 3:
输入: s = “aabb”
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
方法一:哈希表
1.1 思路分析
定义一个哈希表对字符串进行统计,然后遍历字符串s,根据字符串s的顺序去查询哈希表是否有值为1的元素,如果有,返回此时字符串s对应的下标。
1.2 代码实现
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> countMap = new HashMap<Character, Integer>();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
countMap.put(ch, countMap.getOrDefault(ch, 0)+1);
}
for (int i=0; i<s.length(); i++){
if (countMap.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
}
1.3 测试结果
1.4 复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(|Σ|)。其中Σ 是字符集,在本题中 s 只包含小写字母,因此∣Σ∣≤26。我们需要 O(∣Σ∣) 的空间存储哈希映射。