我怎样才能得到一个字符串的所有字谜

Posted

技术标签:

【中文标题】我怎样才能得到一个字符串的所有字谜【英文标题】:How can I get all the anagrams of a string 【发布时间】:2018-05-17 07:28:31 【问题描述】:

我试图找到一个字符串的所有可能的字谜,并仅使用递归将它们存储在一个数组中。

我卡住了,这就是我所拥有的。

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

编辑:我试图找到一个单词的所有排列并将它们插入一个数组而不使用循环。

【问题讨论】:

嗯,对于初学者来说,四个字母的单词会有 24 个不同的字谜。尝试将它们记录到 string arr[10] 会产生令人毛骨悚然的结果。 字谜是单词。这些是排列,而 C++ 恰好有排列的标准算法。 en.cppreference.com/w/cpp/algorithm/next_permutation @chris 使用 STD 带走了所有编码的乐趣。 可以有重复的字母吗? 【参考方案1】:

你应该使用 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;

【讨论】:

没有for循环是否可以做到这一点? 据我了解,它应该需要这种类型的迭代。【参考方案2】:

您需要在permute() 再次调用permute() 之前存储当前值。这就是你失去一些价值观的地方。

【讨论】:

【参考方案3】:

最简单的方法是这样的:

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

希望这真的有帮助。

【讨论】:

以上是关于我怎样才能得到一个字符串的所有字谜的主要内容,如果未能解决你的问题,请参考以下文章

正则表达式 - 查找字谜和子字谜

CTCI 制作字谜 - 得到不正确的输出

你怎么能找到一个单词的所有字谜?

检查需要删除多少个字符才能在 Python 中生成字谜

我怎样才能得到一个字符串旁边的另一个字符串? [复制]

将所有字谜组合在一起[关闭]