在C ++中打印字符串的所有回文分区
在这个问题上,我们得到了回文字符串。并且我们必须打印该字符串的所有分区。在这个问题中,我们将通过切割找到所有可能的回文分区。
让我们举个例子来了解这个问题-
输入:string='ababa'
输出:ababa,baba,ababa…。
解决此问题的方法是检查子字符串是否是回文。并打印子字符串(如果它是子字符串)。
下面的程序将说明解决方案:
示例
#include<bits/stdc++.h>
using namespace std;
bool isPalindrome(string str, int low, int high){
while (low < high) {
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
void palindromePartition(vector<vector<string> >&allPart, vector<string> &currPart, int start, int n, string str){
if (start >= n) {
allPart.push_back(currPart);
return;
}
for (int i=start; i<n; i++){
if (isPalindrome(str, start, i)) {
currPart.push_back(str.substr(start, i-start+1));
palindromePartition(allPart, currPart, i+1, n, str);
currPart.pop_back();
}
}
}
void generatePalindromePartitions(string str){
int n = str.length();
vector<vector<string> > partitions;
vector<string> currPart;
palindromePartition(partitions, currPart, 0, n, str);
for (int i=0; i< partitions.size(); i++ ) {
for (int j=0; j<partitions[i].size(); j++)
cout<<partitions[i][j]<<" ";
cout<<endl;
}
}
int main() {
string str = "abaaba";
cout<<"Palindromic partitions are :\n";
generatePalindromePartitions(str);
return 0;
}输出结果
Palindromic partitions are : a b a a b a a b a aba a b aa b a a baab a aba a b a aba aba abaaba
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下