[Swift]LeetCode1216. 验证回文字符串 III | Valid Palindrome III

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤我的域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xlouxlai-dy.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a string s and an integer k, find out if the given string is a K-Palindrome or not.git

A string is K-Palindrome if it can be transformed into a palindrome by removing at most k characters from it.github

Example 1:微信

Input: s = "abcdeca", k = 2
Output: true
Explanation: Remove 'b' and 'e' characters.

Constraints:ide

  • 1 <= s.length <= 1000
  • s has only lowercase English letters.
  • 1 <= k <= s.length

给出一个字符串 s 和一个整数 k,请你帮忙判断这个字符串是否是一个「K 回文」。spa

所谓「K 回文」:若是能够经过从字符串中删去最多 k 个字符将其转换为回文,那么这个字符串就是一个「K 回文」。code

示例:orm

输入:s = "abcdeca", k = 2
输出:true
解释:删除字符 “b” 和 “e”。

提示:htm

  • 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 }
相关文章
相关标签/搜索