Python solution O(n) time with flexible set of characters


  • 0
    C
        def firstUniqChar(self, s):
            """
            :type s: str
            :rtype: int
            """        
            s_list = list(s)
            c_index = {}
            for i, c in enumerate(s_list):
                if c not in c_index:
                    c_index[c] = [i,1]
                else:
                    c_index[c][1] += 1
            
            index = len(s_list)
            for x in c_index:
                if c_index[x][1] == 1 and c_index[x][0] < index:
                    index = c_index[x][0]
            
            return -1 if index == len(s_list) else index
    

  • 0
    C

    why do you return the last statement if the index equals the length. Would you just return the first character if they are all unique?


  • 0
    C

    @ColorfulCodes Nevermind. That is if all are repeating. Thank you for this solution.


Log in to reply
 

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