Last active
August 29, 2015 14:21
-
-
Save jmtame/f02948523fab690d7a96 to your computer and use it in GitHub Desktop.
cool tricks in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Very fast way to determine if a string contains all unique characters | |
# Space O(1), Time O(N) | |
# Assumes ASCII strings. Unicode would require space of Array.new(1,111,998). | |
def is_unique(str) | |
return false if str.length > 256 | |
chars = Array.new(256) | |
str.each_byte.lazy.each do |c| | |
return false if chars[c] | |
chars[c] = true | |
end | |
true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment