如何获得字符串的所有字符

How can I get all the anagrams of a string

本文关键字:字符 何获得 字符串      更新时间:2023-10-16

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++;
}

希望这确实有帮助。