使用C#或F#查找字符串的置换,包括单个字符 [英] Find string permutation including the single character using C# or F#
本文介绍了使用C#或F#查找字符串的置换,包括单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成包含字符的变量列表一个字符串的所有可能的排列的列表。 例如,如果我有字符串ABC,我想有一个包含所有可能的变化,就像一个列表:A,B,C,AB,BC
I would like to generate a list of all possible permutations of a string containing a variable list of characters. For example if I have the string "ABC", I would like to have a list that contains all the possible variations, like: A, B, C, AB, BC.
感谢您。
推荐答案
下面是一个LINQ版本:
Here's a LINQ version:
Func<string, IEnumerable<string>> perm = t =>
{
Func<string, string, IEnumerable<string>> perm2 = null;
perm2 =
(t0, t1s) =>
from n in Enumerable.Range(0, t1s.Length)
let c = t1s.Substring(n, 1)
let x = t1s.Remove(n, 1)
let h = t0 + c
from r in (new [] { h, }).Concat(perm2(h, x))
select r;
return perm2("", t);
};
使用这样的:
var ps = perm("abc");
和它会执行一个懒惰的计算。
And it will perform a lazy computation.
var ps = perm("abcdefghijklmnopqrstuvwxyz").Take(2);
// Only computes two values when executed
这篇关于使用C#或F#查找字符串的置换,包括单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文