用 C++ 打印字符串的所有回文分区
本例中,我们给定了一个回文串。我们需要打印出此字符串的所有分区。本例中,我们将通过切割字符串来查找字符串的所有可能回文分区。
我们举个例子来理解一下本例 -
输入 - 字符串 = ‘ababa’
输出 - ababa , a bab a, a b a b a ….
对于本例,解决方案是检查子串是否为回文。如果子串为子串,则打印该子串。
示例
以下程序将演示这一解决方案 -
#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
广告