简体   繁体   中英

Assign a unique value to a string s based on its lexicographic order

I want to come up with a function that assigns unique values to a string based on it's lexicographic order. For instance if my function is labelled as get_key(s) , the function should take as input a string s and return a unique integer which will allow me to compare two strings based on those unique integers that I get, in O(1) time.

Some code for clarity:

get_key('aaa')
#Returns some integer

get_key('b')
#Returns another integer > output of get_key('aaa') since 'b' > 'aaa'

Any help would be highly appreciated.

Note: Cannot use python built in function id()

It's impossible.

Why? No matter what number you return for a string, I can always find a new string that's in between those two.

You would need an unlimited number of values, because there's an infinite amount of strings.

If I understand your problem clearly, one idea I come to is to convert the input to hex then from hex to int, this I believe would solve the problem, however, I guess it is impossible to solve it in O(1). The solution I provided (and every possible solution in my mind) needs O(n) since you don't have any specification on the input length and the function will operate depending on the length of the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM