Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

각 단어가 회문(Palindrome)이 되도록 단어를 분할하는 방법의 수를 찾는 C++ 프로그램

<시간/>

여기에서는 각 단어가 회문(Palindrome)이 되는 방식으로 단어를 분할하는 여러 가지 방법을 찾는 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;
   // goes through all indexes and recursively add remaining partitions if current string is palindrome.
   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<<"the number of partitions:"<<endl;
   partition(s, part);
   return 0;
}

출력

the number of partitions:
t u t o r i a l s
tut o r i a l s