Skip to content

Instantly share code, notes, and snippets.

@preston-56
Last active April 9, 2024 14:17
Show Gist options
  • Select an option

  • Save preston-56/a5ca0da88ca333e5a9d1f23abceb2a71 to your computer and use it in GitHub Desktop.

Select an option

Save preston-56/a5ca0da88ca333e5a9d1f23abceb2a71 to your computer and use it in GitHub Desktop.
#Given a string `s`, find the first non-repeating character in it and return its index. If it does not exist, return `-1`.
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
char_index = {}
for i, char in enumerate(s):
if char in char_index:
char_index[char] = float('inf')
else:
char_index[char] = i
min_index = min(char_index.values())
return min_index if min_index != float('inf') else -1
print(firstUniqChar('leetcode')) # Output: 0
print(firstUniqChar("loveleetcode")) # Output: 2
print(firstUniqChar("aabb")) # Output: -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment