使用排列的字符串操作
String manipulation with permutation
给定一个字符串可以从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)));
}
相关文章:
- 字符串操作 - 字符计数
- 字符串操作主题消息
- 在MySql中使用字符串操作函数有什么问题
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 如何使用 Win32 WCHAR 执行字符串操作
- 基本字符串操作有问题 [c++, Visual Studio 2013]
- 字符串操作 C++ 在字符串之后存储整数
- 将字符数复制到新字符串位置的字符串操作,例如 S[0]
- C 比较字符串操作速度
- C++子字符串/字符串操作
- 高级文件和字符串操作
- 使用字符串操作截断整数
- C#和C++中字符串操作的不同基准测试
- 是否有不涉及 I/O 流的 mingw 库原生的就地字符串操作方法
- 如何使用字符串操作来获取输入文本文件的某些部分
- c++中的字符串操作
- 字符串操作性能问题
- 字符串操作,完全不知所措
- std::C++生成器 6 上的字符串操作错误
- 在此字符串操作代码中获取out_of_range错误