Python O(n) time and O(n) space using Dictionary


  • 0
    P
    def firstUniqChar(self, s):
            """
            :type s: str
            :rtype: int
            """
            index_char_stack = {}
            
            for index, char in enumerate(s):
                if char not in index_char_stack:
                    index_char_stack[char] = index
                else:
                    index_char_stack[char] = -1
            
            min_index = len(s)
    
            for char, index in index_char_stack.items():
                if index != -1 and index < min_index:
                    min_index = index 
                    
            return min_index if min_index != len(s) else -1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.