码迷,mamicode.com
首页 > 其他好文 > 详细

字符串的最佳分割数

时间:2016-06-28 18:38:02      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

  

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s ="aab",
Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.

 

答案

int minCut(string s) {
int len = s.length(); // 求解字符串长度
    // 用于描述s.substr(k, j - k+1) 是否能构成回文子串的矩阵
   // flag[k][j] = true -》能构成回文子串
  cout << "len=" << len << endl;
   vector<vector<bool>> flag(len, vector<bool>(len, false));
// 用于记录最佳分割次数的vector
// 初始状态下,长为i的子串的最佳分割次数为:vec[i] = i-1
  vector<int> vec(len + 1);
  for (int i = 0; i<len + 1; ++i){
         vec[i] = i - 1;
}
// 进入动态规划
for (int i = 0; i < len; i++)
{
    for (int j = 0; j <= i; j++)
  {
  // ss中的ss[j]到ss[i]构成的子串(substr(j,i-j+1))能不能构成回文串?
  if (s[i] == s[j] && (i - j<2 || flag[j + 1][i - 1] == true)){
    flag[j][i] = true;
  //此时前i个字符的最佳分割或者为原分割次数vec[i+1],或为前j-1个字符的最佳分割次数+1
    vec[i + 1] = min(vec[i + 1], vec[j] + 1);
  } //end of if
}//end of for(j)
}// end of for(i)


   return vec[len];

// return getmincut(s);

}

技术分享

也附上自己做错的结果,考虑的是递归方法,每次都从一个位置找从这个位置开始的最大的会问字串,替换原来的位置

bool ispal(string s)//判断字串是否会回文
{
     int begin=0;
   int end=s.size()-1;
  while(begin<end)
  {
  if(s[begin]==s[end])
  {
    begin++;
    end--;
   }
  else
    break;
  }
  if(begin>=end)
    return true;
  else
    return false;
}
int getmincut(string s)//递归获得次数
{
    if(s.size()<=1 || ispal(s))
      return 0;
    else
    {
      int next=0;

      for(int i=0;i<s.size();i++)
      {
      if(ispal(s.substr(0,i)))
        next=i;

      }
      return getmincut(s.substr(next))+1;
    }



int minCut(string s) {

 return getmincut(s);

}

字符串的最佳分割数

标签:

原文地址:http://www.cnblogs.com/ranranblog/p/5624298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!