使用排列的字符串操作

String manipulation with permutation

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

给定一个字符串可以从2到7个字符。我需要填充*,使其最多7个字符,并存储所有的排列到一个容器。此外,它不能接受三个或更多连续的*(例如ABCD***不会被推到容器中)。字符的顺序也不能改变。

例如,用'*'填充的字符串'ABCDEF'可以有以下排列:

ABCDEF*
ABCDE*F
ABCD*EF
ABC*DEF
AB*CDEF
A*BCDEF
*ABCDEF

用'*'填充的字符串'ABCD'可以有以下排列(注意:ABCD***不被接受,因为它有3个连续的'*'):

ABC*D**
ABC**D*
AB*CD**
AB*C*D*
AB*C**D
...
**A*BCD

(…总共30个项目将被推入容器)

我试着写一个程序来做这件事。如果字符串有2个字符长,我需要循环2次。例如,

void loop_two_times(const std::string & str = "AB")
{
    for (int i = 0; i < 7; i++)
    {
        for (int j = i+1; j < 7; j++)
        {
            std::string ustring = get7StarsString(); // this string will contain 7 stars
            ustring[i] = str[0];
            ustring[j] = str[1];
            if (!tooMuchStars(ustring))
            {
                permutations.push_back(ustring);
            }
            else {} // do nothing
        }
    }
}

如果字符串有N个字符长,我需要循环N次。但是,我不想检查字符的数量并编写循环2,3,4,5,6次的函数。例如

switch (numOfChars)
{
    case 2: loop_two_times(); break;
    case 3: loop_three_times(); break;
    case 4: loop_four_times(); break;
    case 5: loop_five_times(); break;
    case 6: loop_six_times(); break;
}

请您建议我如何才能有效地实现这一点?

多谢!

您可以使用以下方式:(https://ideone.com/L209jH)

// return a string with '0' replaced with letter, and '1' with '*'.
std::string convert(const std::string& order, const std::string& s)
{
    std::string res;
    std::size_t pos = 0;
    for (std::size_t i = 0; i != order.size(); ++i) {
        if (order[i] == '1') {
            res += '*';
        } else {
            res += s[pos++];
        }
    }
    return res;
}
void print_combinaison(const std::string& msg)
{
    std::string s(msg.size(), '0');
    s.resize(7, '1');
    // s is a string of 7 letter with '0' (representing letter)
    // and '1' representing '*'
    // initial value of s is one of 0000000, 0000001, 0000011, 0000111,
    // 0001111, 0011111, 0111111 or 1111111.
    do
    {
        if (s.find("111") != std::string::npos) continue;
        std::cout << convert(s, msg) << std::endl;
    } while (std::next_permutation(begin(s), end(s)));
}