Given a string s
, find 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:
counter = Counter(s)
for i, c in enumerate(s):
if counter[c] == 1:
return i
return -1
class Solution {
public int firstUniqChar(String s) {
int[] counter = new int[26];
for (char c : s.toCharArray()) {
++counter[c - 'a'];
}
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (counter[c - 'a'] == 1) {
return i;
}
}
return -1;
}
}
function firstUniqChar(s: string): number {
let record = new Map();
for (let cur of [...s]) {
record.set(cur, record.has(cur));
}
for (let i = 0; i < s.length; i++) {
if (!record.get(s[i])) return i;
}
return -1;
}
class Solution {
public:
int firstUniqChar(string s) {
vector<int> counter(26);
for (char& c : s) ++counter[c - 'a'];
for (int i = 0; i < s.size(); ++i)
if (counter[s[i] - 'a'] == 1)
return i;
return -1;
}
};
func firstUniqChar(s string) int {
counter := make([]int, 26)
for _, c := range s {
counter[c-'a']++
}
for i, c := range s {
if counter[c-'a'] == 1 {
return i
}
}
return -1
}
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
const counter = new Map();
for (let c of s) {
counter[c] = (counter[c] || 0) + 1;
}
for (let i = 0; i < s.length; ++i) {
if (counter[s[i]] == 1) {
return i;
}
}
return -1;
};