我需要一个函数来查找字符串的下一个字典值(字符串的长度不应更改)。例如(abc=>acb
,aaba=>abaa
)
答案 0 :(得分:0)
您可以尝试下面的代码,它使用私有字段来搜索由寻找置换方法生成的所有置换:
private static List<string> _permutations = new List<string>();
public static Main(string[] args)
{
string testString = "abc";
TestMethod(testString);
// You need to handle case when you have last permuation in a list
string nextPermutation = _permutations[_permutations.IndexOf(testString) + 1];
}
private static void Swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
private static void GetPer(char[] list)
{
int x = list.Length - 1;
GetPer(list, 0, x);
}
private static void GetPer(char[] list, int k, int m)
{
if (k == m)
{
_permutations.Add(new string(list));
}
else
for (int i = k; i <= m; i++)
{
Swap(ref list[k], ref list[i]);
GetPer(list, k + 1, m);
Swap(ref list[k], ref list[i]);
}
}
private static void TestMethod(string str)
{
char[] arr = str.ToCharArray();
GetPer(arr);
}