我有大量的字符串。就我的目的而言,如果一个是另一个的旋转(例如'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