https://leetcode.com/problems/first-unique-character-in-a-string/
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
- code
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> counter = new LinkedHashMap<>();
for (char c: s.toCharArray()){
counter.put(c, counter.getOrDefault(c, 0) + 1);
}
for (char c: counter.keySet()){
if (counter.get(c) == 1) return s.indexOf(c);
}
return -1;
}
}
- code
class Solution:
def firstUniqChar(self, s: str) -> int:
char_count = dict(collections.Counter(s))
for i in range(len(s)):
if char_count[s[i]] == 1:
return i
return -1
- code
import string
class Solution:
def firstUniqChar(self, s: str) -> int:
ret = len(s)
for c in string.ascii_lowercase:
l, r = s.find(c), s.rfind(c)
if l != -1 and l == r:
ret = min(ret, l)
return ret if ret != len(s) else -1