我在C#中看到了几个字符串变体的实现,但它们都没有对它们的长度有任何限制。不幸的是,我无法修改它们来实现我的目标,例如从字符串中生成特定长度的所有变体
为:
string = "ABCD" and variationLength = 2
生成新的字符串:
AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC
我正在寻找的正是这种Python的和itertools.permutations实现,但在C#。 (https://docs.python.org/3/library/itertools.html#itertools.permutations)
在C#中有类似的东西吗?如果不是,那么实现它的最简单方法是什么?
Edit_2: 到目前为止,我想出了一个主意,列出定字符串的所有独特的字符,然后让变化了出来
static void PrintAllKLengthPerm(string str, int k)
{
int n = str.Length;
PrintAllKLengthPermRec(str, "", n, k);
}
// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
// Base case: k is 0, print prefix
if (k == 0)
{
Console.WriteLine(prefix);
return;
}
// One by one add all characters from str and recursively
// call for k equals to k-1
for (int i = 0; i < n; ++i)
{
// Next character of input added
String newPrefix = prefix + str[i];
// k is decreased, because we have added a new character
PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
}
}
static void Main(string[] args)
{
string str = "ABCD";
int permLen = 2;
//get all unique characters in string
string uniqStr = new String(str.Distinct().ToArray());
// Print all possible strings of length permLen out of uniqStr characters
PrintAllKLengthPerm(uniqStr, permLen);
}
但是我正在寻找更优化,有效地解决
你尝试过这么远吗? – Ani
请显示您的工作。你试过什么了? – Soviut
@Soviut编辑.. –