繁体   English   中英

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

[英]Find All Palindrome Substrings in a String by Rearranging Characters

为了娱乐和练习,我尝试解决以下问题(使用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;
}

该算法有什么问题? 我最关心的是算法的功能,而不是效率。 尽管我也会感谢有关效率的提示。 谢谢。

这在“代码审查”中可能更合适,但这里是:

逻辑错误

您在迭代时更改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”函数(可能效率不高),但是您应该明白这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM