O(n) solution without extra space


  • 0
    class Solution(object):
        def firstUniqChar(self, s):
            one, two = 0, 0
            for char in s:
                bit = 1 << ord(char) - 97
                if not one & bit:
                    if not two & bit:
                        one |= bit
                    continue
    
                one &= ~bit
                two |= bit
    
            for i, char in enumerate(s):
                bit = 1 << ord(char) - 97
                if one & bit:
                    return i
    
            return -1
    

Log in to reply
 

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