给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

提示: 你可以假定该字符串只包含小写字母。

二、方法一

两遍遍历+哈希,先用哈希存储,出现的次数,然后再遍历获取下标

class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。我们需要进行两次遍历。
  • 空间复杂度:O(∣Σ∣),其中Σ 是字符集,在本题中 s 只包含小写字母,因此 ∣Σ∣≤26。我们需要 O(∣Σ∣) 的空间存储哈希映射。

三、方法二

在上面的基础上,进行改变,通过设置是否是 -1来确定是否有重复的元素

class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> map = new HashMap<>();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, -1);
} else {
map.put(c, i);
}

}
int first = n;
for (Map.Entry<Character,Integer> entry : map.entrySet()) {
int index = entry.getValue();
if (index != -1 && index < first) {
first = index;
}
}
if (first == n) return -1;
else return first;

}
}
  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。
  • 空间复杂度:O(∣Σ∣),其中Σ 是字符集,在本题中 s 只包含小写字母,因此 ∣Σ∣≤26。我们需要 O(∣Σ∣) 的空间存储哈希映射。