通过重新排列字符找到字符串中的所有回文子字符串
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;
}
这个算法有什么问题?我最关心的是算法的功能,而不是效率。不过我也希望你能给我一些关于效率的建议。谢谢。
这可能更适合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"函数(可能效率不高),但您应该了解其中的含义。
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 程序以查找给定字符串中回文的子字符串的数量
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 返回字符串的散点回文计数
- C++ 递归布尔回文(字符串 s)
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- 尝试使用C++实现检测字符串中回文的递归版本.在这里遇到了一些麻烦
- 找到字符串中的所有回文
- 验证字符串是否为回文的函数
- 字符串回文程序不会忽略案例
- 字符串中的最小回文计数
- 为给定字符串生成所有可能的回文
- 仅删除一个元素以制作字符串回文
- 使用数组和无指针创建回文字符串检查器C++
- 检查字符串是否为回文
- 回文子字符串程序无法运行
- 带有堆栈和队列的字符串回文(c++)
- 字符串回文在String.size()上给出错误答案,但在String.seize()-1上给出正确答案
- DP方法,用于生成字符串回文时应添加的最小字符数