Advertisement
Guest User

Untitled

a guest
May 28th, 2015
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. # running time must be O(N), as you always have fixed array
  2. # as one of the optimisations is keeping the exact occurrence in separate
  3. # array, so you will not come across problem when a - 1 time, s - 1000000 times
  4. # or more
  5. def sortstring(str):
  6. # allocating list of ASCII characters
  7. # max is just for some kind of optimization, you can also nullify chars
  8. # that you already viewed, or something like that
  9. list, max = 128*[0], 0
  10. # collecting occurence of each character
  11. for i in range(len(str)):
  12. list[ord(str[i])] += 1
  13. max = list[ord(str[i])] if max < list[ord(str[i])] else max
  14. res = ""
  15. # go though potential number of occurrences
  16. # and collect chars, as they are already sorted by char index
  17. # in Java I would use some sort of StringBuffer, if you are dealing with
  18. # very large strings
  19. for i in range(1, max+1):
  20. for j in range(len(list)):
  21. if list[j] == i:
  22. res += chr(j)*i
  23. return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement