我怎样才能得到一个字符串的所有字谜 [英] How can I get all the anagrams of a string
本文介绍了我怎样才能得到一个字符串的所有字谜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一个字符串的所有可能的字谜,并仅使用递归将它们存储在一个数组中.
Im trying to find all the possible anagrams of a string and store them in an array using only recursion.
我卡住了,这就是我所拥有的.
Im stuck and this is all i have.
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
The order doesnt matter. Ex: string "abc"; array should have: abc, acb, bca, bac, cab, cba
我试图找到一个单词的所有排列并将它们插入到一个数组中而不使用循环.
im trying to find all permutations of a word and insert them into an array without using loops.
推荐答案
你应该使用 string&对于参数,因为它会更有效.您应该遍历字符.
You should use string& for the parameter as it will be more efficient. You should iterate through chars.
#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;
}
这篇关于我怎样才能得到一个字符串的所有字谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文