387. First Unique Character in a String
EasyLeetCodeGiven 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:
0Explanation: The character 'l' at index 0 is the first character that does not occur at any other index.
Example 2
Input: s =
"loveleetcode"Output:
2
Example 3
Input: s =
"aabb"Output:
-1
Constraints
1 <= s.length <= 10^5sconsists of only lowercase English letters.
How to solve the problem
- Hash Table with Character Counting
Code
python
class Solution:
def firstUniqChar(self, s: str) -> int:
myHash = {}
for c in s:
myHash[c] = myHash.get(c, 0) + 1
for i, c in enumerate(s):
if myHash[c] == 1:
return i
return -1python
from collections import Counter
class Solution:
def firstUniqChar(self, s: str) -> int:
myHash = Counter(s)
for i, c in enumerate(s):
if myHash[c] == 1:
return i
return -1Complexity
Approach 1: Hash Table with Character Counting
Time complexity: O(n)
Space complexity: O(1) We only store character counts, which is bounded by the size of the alphabet (26 for lowercase English letters).
Comments
No comments yet. Be the first to comment!