词法排列字符串的所有子串的最佳方式

时间:2014-07-16 11:24:01

标签: python string algorithm sorting

我一直试图解决这个问题:

Given a string S , generate a string Y such that:

Y = concatenate( lexically_sorted ( list_of_all_distinct_substrings_of_S ) ) 

1<=length_of_S <= 10^5

Mysolution在小案例中是正确的,例如:

S = dbac

但我的代码在分段错误的大字符串上失败了:

S = judaioobpoiteiszvzlscmpmpqqwuvtdqzdapudfimaowsnttalwndievaapwusmtyoksrpcfpqbkgvfiibvlkbjkcy

输入格式:

T #no of testcases
S #given string S

输出格式:

Y #resultant string Y

MySolution Python代码:

import sys
import itertools

def lex_arrange_substring(s):
    com=[list(itertools.combinations(s,x)) for x in range(1,len(s)+1)]
    substring_list = list(set([''.join(e) for e in sum(com,[])]))
    substring_list = sorted(substring_list)
    final_string = ''
    for x in substring_list:
        final_string = final_string + x
    return final_string

#for reading standard input
inp = sys.stdin.readlines()
t = str(inp[0]).rstrip('\n')
t = int(t)
i = 1    
while i < len(inp):
    s = str(inp[i]).rstrip('\n')
    fstring = lex_arrange_substring(s)
    print fstring
    i = i+1

任何人都可以帮助我理解问题或提供更好的替代解决方案。 在此先感谢!

0 个答案:

没有答案