生成给定字符串的条件排列

Generating conditional permutations of a given string

本文关键字:条件 排列 字符串      更新时间:2023-10-16

我有一个非常直接简单的问题。答案可能不是这样。

如果我有一个字符串,说"随机",并说我想生成字符串的排列,条件是我想要一个,‘a’总是在左起第三位,即在arr[2],如果arr保持字符串。有人可能建议生成所有可能的结果,然后寻找arr[2]='0'的结果,但考虑到我的代码是O(n*n!),我认为我真的不想这么做。

我是C++的中级学生。

这取决于条件的指定方式。例如,您可以创建一个从0length(YOUR_STRING)的数字矢量,而不使用与预先固定的字符相对应的索引。

然后,您可以对该向量应用随机混洗,并在混洗向量指示的位置(加上预先固定的字符)写入一个新字符串,其中包含YOUR_STRING的字符。

一个例子:

std::string yourString = "foo bar bar";
/* pre-fixed characters */
size_t fixedPositionsOrigin[2] = {0, 4}; // "f" and first "b" 
size_t fixedPositionsDestin[2] = {8, 2}; // "f" will be put in position 8, first "b" in position 2
/* Other indices */
std::vector<size_t> remainingIndices = {1, 2, 3, 5, 6, 7, 8, 9, 10}; // valid in C++11 only
std::vectro<size_t> shuffledIndices(remainingIndices); // copy 
std::random_shuffle(shuffledIndices.begin(), shuffledIndices.end());
/* New string */
std::string newString(yourString.size(), " "); // empty string
// Add pre-fixed characters at correct positions
newString[fixedPositionsDestin[idx]] = yourString[fixedPositionsOrigin[idx]]; // something like this in a loop
// add shuffled characters at correct positions 
newString[shuffledIndices[idx]] = yourString[remainingIndices[idx]]; // something like this in a loop

就是这样。当然,有多种方法可以改进代码。我甚至不知道它是否能编译。您可能希望将random_shuffle版本与生成器一起使用,以便"控制"随机数的生成。