我有大量的字符串。就我的目的而言,如果一個是另一個的旋轉(例如'1234'等同於'3412'),則兩個字符串是等價的。當字符串相當於旋轉
什麼是在Python中精確處理每個字符串(一直到旋轉)的有效方法?
一個天真的實現什麼,我想可能是這樣的:
class DuplicateException(Exception): pass
seen = set()
for s in my_strings:
try:
s2 = s+s
for t in seen:
# Slick method I picked up here in SO
# for checking whether one string is
# a rotation of another
if len(s) == len(t) and t in s2:
raise DuplicateException()
seen.add(s)
process(s)
except DuplicateException: pass
這是每個字符串的O(n²),實際上可以更快地計算它,請參閱維基百科「字典順序最小字符串旋轉」 – 2013-03-03 14:37:12
@FalkHüffner,必須有一些東西! – Akavall 2013-03-03 17:02:34
只需將鏈接添加到FalkHüffner建議的帖子中:http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation – 2013-04-01 02:36:10