在这里,我们将讨论一个C ++程序,以找到对单词进行分区的多种方法,以使每个单词都是回文。
Begin Take the word as input. Function partitionadd(vector<vector<string> > &u, string &s, vector<string> &tmp, int index): if (index == 0) tmp.clear() for i = index to length-1 st = st + s[i] if (checkPalin(st)) tmp.push_back(st) if (i+1 < length) partitionadd(u, s, tmp, i+1) else u.push_back(tmp) tmp = curr return End Begin Function partition(string st, vector<vector<string> >&u): vector<string> tmp addStrings(u, st, tmp, 0) printSol(u) //to print the solution return End
#include <bits/stdc++.h> using namespace std; bool checkPalin(string s) { //check if string is palindrome or not. int length = s.length(); length--; for (int i=0; i<length; i++) { if (s[i] != s[length]) return false; length--; } return true; } void printSol(vector<vector<string> > part) { //print the solution for (int i = 0; i < part.size(); ++i) { for(int j = 0; j < part[i].size(); ++j) cout << part[i][j] << " "; cout << endl; } return; } void partitionadd(vector<vector<string> > &u, string &s, vector<string> &tmp, int index) { int length = s.length(); //store length of the string string st; vector<string> curr = tmp; //如果当前字符串是回文,则遍历所有索引并递归添加其余分区。 if (index == 0) tmp.clear(); for (int i = index; i < length; ++i) { st = st + s[i]; if (checkPalin(st)) { tmp.push_back(st); if (i+1 < length) partitionadd(u,s,tmp,i+1); else u.push_back(tmp); tmp = curr; } } return; } void partition(string st, vector<vector<string> >&u) //generate all palindromic partitions of 'str' and stores the result in 'm'. { vector<string> tmp; addStrings(u, st, tmp, 0); printSol(u); return; } int main() { string s = "tutorials"; vector<vector<string> > part; cout<<"t分区数:"<<endl; partition(s, part); return 0; }
输出结果
t分区数: t u t o r i a l s tut o r i a l s