用 C++ 列印字串的所有迴文分割槽


本例中,我們給定了一個迴文串。我們需要打印出此字串的所有分割槽。本例中,我們將透過切割字串來查詢字串的所有可能迴文分割槽。

我們舉個例子來理解一下本例 -

輸入 - 字串 = ‘ababa’
輸出 - ababa , a bab a, a b a b a ….

對於本例,解決方案是檢查子串是否為迴文。如果子串為子串,則列印該子串。

示例

以下程式將演示這一解決方案 -

 Live Demo

#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

更新於: 14-Jul-2020

131 次檢視

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.