当前位置:网站首页>132. 分割回文串 II
132. 分割回文串 II
2022-07-22 05:58:00 【小卢要刷力扣题】
题目
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。
返回符合要求的 最少分割次数 。
示例 1:
输入:s = “aab”
输出:1
解释:只需一次分割就可将 s 分割成 [“aa”,“b”] 这样两个回文子串。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-partitioning-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
动态规划,从左到右模型
尝试的是每一个作为切出来的第1部分,所有的可能性
dp[i]从出发后面所有的字符串至少分成几个部分让每个部分都是回文
不优化的化为O(n3)
需要优化检查回文的逻辑
预处理表
生成一个map,告诉你从i到j是否为回文
构建正方形表
填好第一条对角线和第二条对角线
普遍位置
map[l][r]=str[l]==str[r]&&map[l+1][r-1]
boolean[][] isMap=new boolean[n][n];
for(int i=0;i<n-1;i++){
isMap[i][i]=true;
isMap[i][i+1]=str[i]==str[i+1];
}
isMap[n-1][n-1]=true;
for(int i=n-3;i>=0;i--){
for(int j=i+2;j<n;j++){
isMap[i][j]=(str[i]==str[j]&&isMap[i+1][j-1]);
}
}
代码
class Solution {
public int minCut(String s) {
char[] str=s.toCharArray();
int n=str.length;
if(n==0||n==1){
return 0;
}
boolean[][] isMap=new boolean[n][n];
for(int i=0;i<n-1;i++){
isMap[i][i]=true;
isMap[i][i+1]=str[i]==str[i+1];
}
isMap[n-1][n-1]=true;
for(int i=n-3;i>=0;i--){
for(int j=i+2;j<n;j++){
isMap[i][j]=(str[i]==str[j]&&isMap[i+1][j-1]);
}
}
int[] dp=new int[n];
for(int i=n-1;i>=0;i--){
if(isMap[i][n-1]){
dp[i]=1;
}else{
int next=Integer.MAX_VALUE;
for(int j=i;j<n;j++){
if(isMap[i][j]){
next=Math.min(dp[j+1],next);
}
}
dp[i]=next+1;
}
}
return dp[0]-1;
}
}
边栏推荐
猜你喜欢
JWT learning
Activity recommendation | Apache pulsar's exploration and practice in vivo will be broadcast soon
Matlab function: filtfilter -- zero phase digital filtering
Simple use of UE4 terrain tool
JWT学习
16_ Response status code
Spark高级特性,220720,
polygon 链 matic概念及底层机制
Abaqus实现二自由度振动系统模态计算
UE4 enters the designated area to realize the trigger acceleration function
随机推荐
16_ Response status code
How to download and install xshell plus6
Classification of iris based on tensorflow neural network
JS的DOM操作——事件链(冒泡目标捕获)
pytorch优化器: optim.SGD && optimizer.zero_grad()
[web page performance optimization] - about lazy image loading
UE4 create a project
2022/7/19-日报
接招吧。最强“高并发”系统设计 46 连问,分分钟秒杀一众面试者
Pytoch deep learning practice lesson 11 (CNN)
LVS, this is enough
分享我们的首次Otherside之旅
Overview of basic principles of network
MySQL中的日志“binlog”的三种格式这么好玩
[machine learning] how pytorch loads custom datasets and divides them
Nvidia 硬件架构
工作流引擎在vivo营销自动化中的应用实践 | 引擎篇03
UE4 keyboard keys realize door opening and closing
UE4 key to open the door
Simple use of UE4 terrain tool