繁体   English   中英

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

[英]Assign a unique value to a string s based on its 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 .

为了清楚起见,一些代码:

get_key('aaa')
#Returns some integer

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

任何帮助将不胜感激。

注意:不能使用 function id() 内置的 python

不可能。

为什么? 无论您为字符串返回什么数字,我总能找到介于这两者之间的新字符串。

您将需要无限数量的值,因为有无限数量的字符串。

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

暂无
暂无

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

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