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

Palindrome Partitioning II--LeetCode

时间:2015-04-11 18:01:45      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:算法   leetcode   c++   

题目:

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",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

思路:和上面一题一样,找出所有的可能,从中找出分割次数最少的。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool check(string& str,int begin,int end)
{
     int i = begin ;
     int j = end;
     for(;i<=j;i++,j--)
      if(str[i] != str[j])
        return false;
      return true;
}

void helper(string& str,int begin,int end,vector<int>& pos,int& count)
{
    int i,j,k;
    if(begin > end)
    {
        int k =0;
        for(j=0;j<pos.size();j++)
        {
           if(pos[j] != -1 && j != pos.size()-1)
           {
            k++;
            pos[j] = -1; 
           }
           /*
           cout<<str[j];
           if(pos[j] != -1)
           {
             cout<<",";
             pos[j] = -1;
           } */                       
        }   
         if(k < count)
         count = k; 
       // cout<<endl;     
    }
    for(i= begin;i<=end;i++)
    {
        if(check(str,begin,i))
        {
            pos[i] = i-begin+1;
            helper(str,i+1,end,pos,count);  
        }  
    }     
}

int PalindromePartition(string& str)
{
     if(str.length() == 0)
      return 0;
     vector<int> pos(str.length(),-1);
     int count=str.length()-1;
     helper(str,0,str.length()-1,pos,count);
     return count;
}

int main()
{
    string str("aab");
    cout<<PalindromePartition(str);
    system("pause");
    return 0;
}




Palindrome Partitioning II--LeetCode

标签:算法   leetcode   c++   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44996299

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