文字列のすべてのパリンドロームパーティションをC++で出力します
この問題では、回文文字列が与えられます。そして、この文字列のすべてのパーティションを出力する必要があります。この問題では、弦を切断することにより、弦のすべての可能な回文パーティションを見つけます。
問題を理解するために例を見てみましょう-
入力 −文字列=「ababa」
出力 − ababa、a bab a、a b aba…。
この問題の解決策は、部分文字列が回文であるかどうかを確認することです。部分文字列の場合は、部分文字列を出力します。
#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
-
文字列を逆にする(反復)C ++
スタック、インプレース、反復など、C++コードの文字列を逆にする方法はたくさんあります。このサンプルでは、次のアルゴリズムを使用して単純な文字列を繰り返し反転します。 アルゴリズム START Step-1: Input the string Step-2: Get the length of the string using length() method Step-3: Swap the last character to first using for loop Step-4: P
-
特定の文字列のすべてのサブ文字列をC++で出力するプログラム
このチュートリアルでは、特定の文字列のすべての部分文字列を出力するプログラムについて説明します。 このために、文字列または文字の配列が提供されます。私たちのタスクは、その特定の文字列のすべてのサブ文字列を出力することです。 例 #include<bits/stdc++.h> using namespace std; //printing all the substrings void print_substr(char str[], int n){ for (int len = 1; len <= n; len++){