输入一个字符串,输出该字符串中相邻字符的所有组合。
举个例子,如果输入abc,它的组合有a、b、c、ab、bc、abc。(注意:输出的组合需要去重)(40分)
注意,这道题贼坑。题目中说“每个组合以空格分隔”,但其实在结尾还要加一个空格才可以!!
首先要找到所有相邻字符串的列表。使用两层循环遍历即可。(还要去重)
多key排序。根据长度和字典序排序,在python中再简单不过。
六行:
string = input()
res = set()
for i in range(1, len(string) + 1):
for j in range(len(string) - i + 1):
res.add(string[j:j + i])
print(" ".join(sorted(list(res), key=lambda c: (len(c), c))))
可以使用列表表达式简化成三行:
string = input()
res = {string[j:j + i] for i in range(1, len(string) + 1) for j in range(len(string) - i + 1)}
print(" ".join(sorted(list(res), key=lambda c: (len(c), c)))+" ")
python实现的思路,遍历长度为1,2,n的连续子串,遍历每个子串时将结果 加入一个临时列表temp时,遍历结束时,利用列表的sort()方法对临时列表 temp进行排序,并加入到结果列表中。 s = input() n = len(s) res = [] for i in range(1, n+1): temp = [] for j in range(n-i+1): s_t = s[j:j+i] if s_t not in temp : temp.append(s_t) temp.sort() res.extend(temp) res = ' '.join(res) res +=' ' print(res)