[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 }
相關文章
相關標籤/搜索