Palindrome Partitioning II--LeetCode

本文介绍了一个算法问题,即如何计算将字符串分割成多个回文子串所需的最少分割次数。通过递归方法检查所有可能的分割,并使用辅助函数验证每个子串是否为回文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

其实这个题目比上一个题目更加简单,因为之间看分割的最少次数,同样的分割方式,只不过需要关注的是分割的最少次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值