字符串字符全组合(python) |
您所在的位置:网站首页 › js输入一个字符串,求出该字符串包含的字符集合 › 字符串字符全组合(python) |
1. 相邻字符的组合
输入一个字符串,输出该字符串中相邻字符的所有组合。 举个例子,如果输入abc,它的组合有a、b、c、ab、bc、abc。(注意:输出的组合需要去重) 输入描述: 一个字符串 输出描述: 一行,每个组合以空格分隔,相同长度的组合需要以字典序排序,且去重。 示例1 输入 bac 输出 a b c ac ba bac链接:https://www.nowcoder.com/questionTerminal/837f4d04f5cb4f26a8215b2b95cc76a5 来源:牛客网 2. 题解 import sys s = input() res = [] for i in range(1,len(s)+1): for j in range(len(s)-i+1): if s[j:j+i] not in res: res.append(s[j:j+i]) res = list(sorted(res,key=lambda x:(len(x),x))) print(" ".join(res)+" ") 3. 非相邻字符的所有组合输入一个字符串,打印出该字符串中字符的所有组合。 例如: 输入三个字符a, b, c, 则它们的组合有 a, b, c, ab, ac, bc, abc。当交换字符串中的字符时,虽然能得到两个不同的排列,但却是同一个组合。比如 ab 和 ba 是不同的排列,但只算一个组合。 思路 组合可以分为,包含当前的字符和不包含当前字符,但最终的组合字符长度需要大于0。 可以用递归解决。 def get_combination(str,res=[],str_comb=""): if len(str_comb) >0 and str_comb not in res: res.append(str_comb) if len(str) == 0: return res comb1 = str_comb+ str[0] res = get_combination(str[1:],res,comb1) res = get_combination(str[1:],res, str_comb) return res def test(): string = ["a","b","c","d"] res = get_combination(string,[],"") print(res,len(res)) if __name__ == "__main__": test()输出: ['a', 'ab', 'abc', 'abcd', 'abd', 'ac', 'acd', 'ad', 'b', 'bc', 'bcd', 'bd', 'c', 'cd', 'd'] 15 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |