LeetCode 1216. Valid Palindrome III
2024-10-16 23:02:46
原题链接在这里:https://leetcode.com/problems/valid-palindrome-iii/
题目:
Given a string s
and an integer k
, find out if the given string is a K-Palindrome or not.
A string is K-Palindrome if it can be transformed into a palindrome by removing at most k
characters from it.
Example 1:
Input: s = "abcdeca", k = 2
Output: true
Explanation: Remove 'b' and 'e' characters.
Constraints:
1 <= s.length <= 1000
s
has only lowercase English letters.1 <= k <= s.length
题解:
Find the longest palindrome from s.
And check the difference between s and longest palindrome length, if it is <= k, then return true.
Time Complexity: O(n^2). n = s.length().
Space: O(n^2).
AC Java:
class Solution {
public boolean isValidPalindrome(String s, int k) {
if(s == null || s.length() <= k){
return true;
} int lp = findLongestPalin(s);
return s.length() - lp <= k;
} private int findLongestPalin(String s){
if(s == null || s.length() == 0){
return 0;
} int n = s.length();
int [][] dp = new int[n][n];
for(int i = n-1; i>=0; i--){
dp[i][i] = 1;
for(int j = i+1; j<n; j++){
if(s.charAt(i) == s.charAt(j)){
dp[i][j] = dp[i+1][j-1] + 2;
}else{
dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
}
}
} return dp[0][n-1];
}
}
类似Longest Palindromic Subsequence, Valid Palindrome, Valid Palindrome II.
最新文章
- PHP面试题4
- Openjudge 1.13-40 提取数字串按数值排序
- HashMap合并相同key的value
- 深入浅出设计模式——策略模式(Strategy Pattern)
- IOS弹出视图 LewPopupViewController
- [转]Linux之type命令
- 存量数据处理结果查询.txt
- 获取电脑cpu的使用情况
- html---id,name和value
- Python处理海量手机号码
- java集合概念
- docker~从Dockerfile到Container的过程(终于算是OK了)
- 201521123054 《Java程序设计》第14周学习总结
- php中一些提高性能的技巧
- 阿里巴巴Java开发规约插件
- 开源框架Volley的使用《二》[NetWorkImageView&;&;LruCache&;ImageLoader]
- 《前端之路》之 Babel 下一代 JavaScript 语法编译器
- linux中gcc和g++的区别
- Java NIO系列教程(七) selector原理 Epoll版的Selector
- Django中的缓存基础知识
热门文章
- BScroll使用
- idea类存在找不到解决办法
- Angular中上传图片到分布式文件服务器FastDFS上
- Java基础语法面试题
- WPF DataGrid 使用CellTemplateSelector 时SelectTemplate方法Item参数为NULL
- 【题解】C2Crni - Crni [COCI2010] [SP7884]
- 【05】C#特有的ref、out参数
- Cases:Unit Testing with the MSTest Framework
- .Net FrameWork获取配置文件信息
- 深挖Jvm垃圾收集