Guest User

Untitled

a guest
Nov 18th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from collections import OrderedDict
  5.  
  6.  
  7. def find_index_of_first_unique_char(string):
  8. seen_once = OrderedDict() # LinkedHashMap
  9. seen_many = set() # HashSet
  10. for index, char in enumerate(string): # O(N)
  11. if char in seen_many: # O(1)
  12. continue
  13. elif char in seen_once: # O(1)
  14. seen_many.add(char) # O(1)
  15. seen_once.pop(char) # O(1)
  16. else:
  17. seen_once[char] = index # O(1)
  18. if not seen_once: # O(1)
  19. return -1
  20. else:
  21. # get the first item
  22. return seen_once.popitem(last=False)[1] # O(1)
  23.  
  24.  
  25. assert find_index_of_first_unique_char("") == -1
  26. assert find_index_of_first_unique_char("aa") == -1
  27. assert find_index_of_first_unique_char("baa") == 0
  28. assert find_index_of_first_unique_char("zabcddd") == 0
  29. assert find_index_of_first_unique_char("this is my string") == 1
  30. assert find_index_of_first_unique_char("this this is my string") == 13
  31. assert find_index_of_first_unique_char("this this is my string add an m") == 14
Add Comment
Please, Sign In to add comment