字符串的最佳分割数

  

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);

}

posted @ 2016-06-28 17:41  ranran1203  阅读(269)  评论(0编辑  收藏  举报