如何获得字符串的所有字符
How can I get all the anagrams of a string
im试图找到字符串的所有可能的字词,并仅使用递归将它们存储在数组中。
我卡住了,这就是我所拥有的。
int main()
{
const int MAX = 10;
string a = "ABCD";
string arr[10];
permute(arr, a, 0, a.size(), 0);
return 0;
}
void permute(string arr[], string wrd, int firstLetter, int lastLetter, int it)
{
if (firstLetter == lastLetter)
*arr = wrd;
else
{
swap(wrd[firstLetter], wrd[it]);
permute(arr, wrd, firstLetter + 1, lastLetter, it++);
}
}
订单无关紧要。例如:字符串" ABC";阵列应具有:ABC,ACB,BCA,BAC,CAB,CBA
编辑:我试图找到单词的所有排列,并在不使用循环的情况下将它们插入数组中。
您应该使用String&对于参数,它将更有效。您应该通过字符迭代。
#include <iostream>
#include <string>
using namespace std;
void permute(string* arr, int& ind, string& wrd, int it) {
if (it == wrd.length()) {
arr[ind++] = wrd;
} else {
for (int i = it; i < wrd.length(); ++i) {
swap(wrd[i], wrd[it]);
permute(arr, ind, wrd, it + 1);
swap(wrd[i], wrd[it]);
}
}
}
int main() {
string a = "ABCD";
string arr[100]; // enough size to store all permutations
int ind = 0;
permute(arr,ind, a, 0);
for (int i = 0; i < ind; ++i) {
cout << arr[i] << endl;
}
return 0;
}
您需要在permute()
再次调用permute()
之前存储当前值。这是您失去一些价值的地方。
最简单的方法就是这样:
// Precondition locs size is the same x length and arr is the right size to handle all the permutations
void permute(string arr[], string x, int locs[], int size, int & index)
{
for(int i = 0; i<size; i++)
{
if(locs[i] < size) locs[i]++;
else locs[i] = 0;
}
arr[index] = "";
for(int i = 0; i<size; i++)
{
arr[index] += x[locs[i]];
}
index++;
}
希望这确实有帮助。
相关文章:
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 生成组合的虚拟按键以获得 â、ó、ć 等字符
- 在CPP中获得无限的字符
- C 程序仅在字符阵列获得“ 1000!”的输入时才在DELETE上崩溃
- 我可以搜索字符向量的向量以找到特定的字符并获得其坐标
- 如何获得具有字符和对象的线条功能
- 试图将字符串变为char数组,请帮助我仅在数组中获得所需的字符
- 如何在C 中获得字符串的最后一个字符
- 如何获得字符串的所有字符
- 如何通过在ASCII表中拥有该字符的价值来获得字符
- 为什么我在尝试将字符传递给我的函数以及如何修复它时会获得 SIGSEGV
- 字符 * 和字符串在C++中有何不同?(在描述中编写代码)
- 我无法获得基于读取字符数组的算法来工作
- 如何在字符串C 中获得字符的值
- 当想要以类似的字符终止时,获得无限循环在C 中
- 从字符转换为 TCHAR 中获得奇怪的字符
- cin.get 获得一个额外的字符
- 如何获得一些用空格分隔的字符
- 从字符串中删除两个字符以获得唯一字符的可能性