First Unique Character in a String
387. First Unique Character in a String
Difficulty: Easy
Related Topics: Hash Table, String, Queue, Counting
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
Code:
class Solution:
def firstUniqChar(self, s: str) -> int:
chardict = {}
for i in s:
if i in chardict:
chardict[i]=-1
else:
chardict[i]=s.index(i)
for i in chardict:
if chardict[i] != -1:
return chardict[i]
return -1
Feedbacks:
I made a dictionary to store keys and values. If key is laready in the dictionary, I make the value of that key to -1. So after traversing through the whole string, I return the first value that is not -1. If all of the values are -1, I return -1.