[Swift]LeetCode1216. 验证回文字符串 III | Valid Palindrome III
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11608028.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
给出一个字符串 s
和一个整数 k
,请你帮忙判断这个字符串是不是一个「K 回文」。
所谓「K 回文」:如果可以通过从字符串中删去最多 k
个字符将其转换为回文,那么这个字符串就是一个「K 回文」。
示例:
输入:s = "abcdeca", k = 2 输出:true 解释:删除字符 “b” 和 “e”。
提示:
1 <= s.length <= 1000
s
中只含有小写英文字母1 <= k <= s.length
Runtime: 112 ms
Memory Usage: 21.3 MB
1 class Solution { 2 func isValidPalindrome(_ s: String, _ k: Int) -> Bool { 3 let n:Int = s.count 4 var s:[Character] = Array(s) 5 var dp:[Int] = [Int](repeating: 1, count: n) 6 for i in 0..<n 7 { 8 var last:Int = 0 9 for j in stride(from: i - 1, through: 0, by: -1) 10 { 11 var t:Int = dp[j] 12 if s[i] == s[j] 13 { 14 dp[j] = last + 2 15 } 16 else 17 { 18 dp[j] = max(dp[j], dp[j + 1]) 19 } 20 last = t 21 } 22 } 23 return n - dp[0] <= k 24 } 25 }