Given a string s
, return the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode" Output: 0
Example 2:
Input: s = "loveleetcode" Output: 2
Example 3:
Input: s = "aabb" Output: -1
Constraints:
1 <= s.length <= 105
s
consists of only lowercase English letters.
class Solution:
def firstUniqChar(self, s: str) -> int:
chars = {}
for ch in s:
ch = ord(ch)
chars[ch] = chars.get(ch, 0) + 1
for i, ch in enumerate(s):
ch = ord(ch)
if chars[ch] == 1:
return i
return -1
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> chars = new HashMap<>(26);
int n = s.length();
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
chars.put(ch, chars.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
if (chars.get(ch) == 1) return i;
}
return -1;
}
}