【问题标题】: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++ 恰好有排列的标准算法。
  • @chris 使用 STD 带走了所有编码的乐趣。
  • 可以有重复的字母吗?

标签: c++ recursion anagram


【解决方案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++;
    }
    

    希望这真的有帮助。

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2011-05-15
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多