C++ 程序查找分割单词的方法数量,使得每个单词都是回文

c++server side programmingprogramming

这里我们将讨论一个 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) //打印解决方案
   return
End

示例

#include <bits/stdc++.h>
using namespace std;

bool checkPalin(string s) { //检查字符串是否为回文。
   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) { //打印解决方案
   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 partionadd(vector<vector<string> > &u, string &s, vector<string> &tmp, int index) {
   int length = s.length(); //存储字符串的长度
   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<<"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

相关文章