问题描述:
根据输入的字符串,对字符串进行全排列,输出所有字符串。
例如,输入"ab",输出"ab", "ba";输入"abc",输出"abc", "acb", "bac", "bca", "cab", "cba"。
代码:
static void Main()
{
string word = Console.ReadLine();
while (!string.IsNullOrEmpty(word))
{
foreach (var item in getFullPermutation(word))
{
Console.Write(item + ", ");
}
Console.WriteLine();
word = Console.ReadLine();
}
}
static IEnumerable<string> getFullPermutation(string word)
{
if (word.Length < 2) yield return word;
else
{
char current = word[0];
foreach (var item in getFullPermutation(word.Substring(1)))
{
char[] tmp = new char[word.Length];
for (int i = 0; i < item.Length; i++)
tmp[i] = item[i];
tmp[word.Length - 1] = current;
for (int i = item.Length; i >= 0; i--)
{
if (i < item.Length)
{
tmp[i + 1] = tmp[i];
tmp[i] = current;
}
string result = string.Empty;
for (int j = 0; j < tmp.Length; j++)
result += tmp[j];
yield return result;
}
}
}
}