LeetCode Palindrome Partitioning II

本文介绍了一种通过动态规划解决回文划分问题的方法,并提供了详细的算法解释和代码实现。重点在于利用状态数组和状态转移方程来求解最优划分方案。

摘要生成于 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.
http://oj.leetcode.com/problems/palindrome-partitioning-ii/

题意分析:对输入的字符串进行划分,要求划分后的所有的子字符串都是回文串。求最小划分的个数。
类似于: LeetCode Word Break , 也是利用动态规划。
定义状态数组:cut_num_array[s.length()+1],其中:cut_num_array[i]代表:string[i..n]字符串从i开始到末尾的最小划分数。 
状态转移方程: cut_num_array[i] = Math.min(cut_num_array[i], cut_num_array[j+1]+1);  i<j<n
状态转移方程的意思是,string[i..j]是一个回文字符串,所以不用再划分。所以从i开始到末尾以j为划分点的最小划分数为: cut_num_array[j+1]+1 和 cut_num_array[i]中的最小值。
cut_num_array[i]的初值设为:s.length() - i; 也就是按照字符串中的每个字母都单独被划分来计算。
判断string[i..j]是一个回文串,用 LeetCode Palindrome Partitioning 中的方法,上AC代码。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class Solution {  
  2.     public int minCut(String s) {  
  3.         if(s==null||s.length()==0||s.length()==1) {  
  4.             return 0;  
  5.         }  
  6.         int[][] palindrome_map = new int[s.length()][s.length()];  
  7.         int[] cut_num_array = new int[s.length() + 1];  
  8.           
  9.         for(int i=s.length()-1;i>=0;i--) {  
  10.             cut_num_array[i] = s.length() - i;  
  11.             for(int j=i;j<s.length();j++) {  
  12.                 if(s.charAt(i)==s.charAt(j)) {  
  13.                     if(j-i<2||palindrome_map[i+1][j-1]==1) {  
  14.                         palindrome_map[i][j]=1;  
  15.                         cut_num_array[i] = Math.min(cut_num_array[i], cut_num_array[j+1]+1);  
  16.                     }  
  17.                 }  
  18.             }  
  19.               
  20.         }  
  21.       
  22.         return cut_num_array[0] - 1;  
  23.     }  
  24. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值