简体   繁体   English

根据字典顺序为字符串 s 分配唯一值

[英]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.我想提出一个 function 根据它的字典顺序为字符串分配唯一值。 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. 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()注意:不能使用 function id() 内置的 python

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).如果我清楚地理解您的问题,我想到的一个想法是将输入转换为十六进制,然后从十六进制转换为 int,我相信这可以解决问题,但是,我想在 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.我提供的解决方案(以及我认为的所有可能的解决方案)需要 O(n),因为您对输入长度没有任何规范,并且 function 将根据输入的长度运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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