簡體   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