通过重新排列字符找到字符串中的所有回文子字符串

Find All Palindrome Substrings in a String by Rearranging Characters

本文关键字:字符串 回文 字符 新排列 排列      更新时间:2023-10-16

为了乐趣和实践,我试图解决以下问题(使用c++): Given a string, return all the palindromes that can be obtained by rearranging its characters.

我想出了一个不能完全工作的算法。有时,它会找到所有的回文,但有时它会找到一些,但不是全部。

它通过交换每个相邻字符对N次来工作,其中N是输入字符串的长度。下面是代码:

std::vector<std::string> palindromeGen(std::string charactersSet) {
    std::vector<std::string> pals;
    for (const auto &c : charactersSet) {
        for (auto i = 0, j = 1; i < charactersSet.length() - 1; ++i, ++j) {
            std::swap(charactersSet[i], charactersSet[j]);
            if (isPalandrome(charactersSet)) {
                if (std::find(pals.begin(), pals.end(), charactersSet) == pals.end()) {
                    // if palindrome is unique
                    pals.push_back(charactersSet);
                }
            }
        }
    }
    return pals;
}

这个算法有什么问题?我最关心的是算法的功能,而不是效率。不过我也希望你能给我一些关于效率的建议。谢谢。

这可能更适合Code Review,但这里是:

逻辑错误

您在迭代charactersSet时更改它,这意味着您的迭代器中断。您需要复制characterSet,并遍历它。

需要改变的东西

由于pals只保存唯一的值,它应该是std::set而不是std::vector。这将简化一些事情。此外,您的isPalandrome方法拼写回文错误!

替代方法

由于回文只能采用某种形式,因此请考虑先对输入字符串进行排序,以便可以拥有出现次数为偶数的字符列表和出现次数为奇数的字符列表。您只能有一个字符出现的次数为奇数(这只适用于奇数长度的输入)。这会让你放弃很多可能性。然后,您可以处理一半回文的不同可能组合(因为您可以从另一半中构建一半)。

下面是利用std::next_permutation的另一个实现:

#include <string>
#include <algorithm>
#include <set>
std::set<std::string> palindromeGen(std::string charactersSet) 
{
    std::set<std::string> pals;
    std::sort(charactersSet.begin(), charactersSet.end());
    do
    {
        // check if the string is the same backwards as forwards
        if ( isPalindrome(charactersSet)) 
           pals.insert(charactersSet);
    } while (std::next_permutation(charactersSet.begin(), charactersSet.end()));
    return pals;
}

首先对原始字符串进行排序。这是std::next_permutation正常工作所必需的。调用isPalindrome函数并对字符串进行排列是在循环中完成的。如果字符串是回文,它就存储在集合中。后续对std::next_permutation的调用只是重新排列字符串。

下面是一个实例。当然,它使用字符串的反向副本作为"isPalindrome"函数(可能效率不高),但您应该了解其中的含义。