1

In Python

s= "ABCC"
n = len(s)
sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])

gives me, alphabetically sorted sub strings with out repetitions

['A', 'AB', 'ABC', 'ABCC', 'B', 'BC', 'BCC', 'C', 'CC']

How can I further sort it by length of sub string.

['A', 'B', 'C', 'AB', 'BC', 'CC', 'ABC', 'BCC', 'ABCC']
4

2 回答 2

3

simple,

sorted(set(s[a:b] for a in range(n) for b in range(a+1,n+1)),
       key=lambda x:(len(x),x))

This creates a key by which the comparison is done. First it compares the string lengths to determine the order. If the strings have the same length, the tie-breaker is the string contents.

于 2013-02-05T15:19:05.623 回答
2

This is your solution:

s= "ABCC"
n = len(s)
sorted(sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])),key=len)
于 2013-02-05T15:23:29.517 回答