Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- from collections import OrderedDict
- def find_index_of_first_unique_char(string):
- seen_once = OrderedDict() # LinkedHashMap
- seen_many = set() # HashSet
- for index, char in enumerate(string): # O(N)
- if char in seen_many: # O(1)
- continue
- elif char in seen_once: # O(1)
- seen_many.add(char) # O(1)
- seen_once.pop(char) # O(1)
- else:
- seen_once[char] = index # O(1)
- if not seen_once: # O(1)
- return -1
- else:
- # get the first item
- return seen_once.popitem(last=False)[1] # O(1)
- assert find_index_of_first_unique_char("") == -1
- assert find_index_of_first_unique_char("aa") == -1
- assert find_index_of_first_unique_char("baa") == 0
- assert find_index_of_first_unique_char("zabcddd") == 0
- assert find_index_of_first_unique_char("this is my string") == 1
- assert find_index_of_first_unique_char("this this is my string") == 13
- assert find_index_of_first_unique_char("this this is my string add an m") == 14
Add Comment
Please, Sign In to add comment