[LeetCode] 1332. Remove Palindromic Subsequences

Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.

Return the minimum number of steps to make the given string empty.

A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.

A string is called palindrome if is one that reads the same backward as well as forward. 

Example 1:

Input: s = "ababa"
Output: 1
Explanation: String is already palindrome

Example 2:

Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "". 
Remove palindromic subsequence "a" then "bb".

Example 3:

Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "". 
Remove palindromic subsequence "baab" then "b".

Example 4:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 1000
  • s only consists of letters 'a' and 'b'

删除回文子序列。

给你一个字符串 s,它仅由字母 'a' 和 'b' 组成。每一次删除操作都可以从 s 中删除一个回文 子序列。

返回删除给定字符串中所有字符(字符串为空)的最小删除次数。

「子序列」定义:如果一个字符串可以通过删除原字符串某些字符而不改变原字符顺序得到,那么这个字符串就是原字符串的一个子序列。

「回文」定义:如果一个字符串向后和向前读是一致的,那么这个字符串就是一个回文。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-palindromic-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题算是个脑筋急转弯。注意题设给的是你可以删除任意一个回文子序列,也就是说你可以跳着找字母删除,只要最后被删除的部分组合起来是个回文就行。这道题由于又只有a和b两种字母,所以我们实际上最多只需要删除两次就可使得最后的字符串为空。

如果input字符串本身就是回文,删除一次

如果input字符串不是回文,那么我们首先把所有的a删除。因为所有的相同字母组合起来一定是个回文串,所以只需要删除两次即可

时间O(1)

空间O(1)

Java实现

1 class Solution {
2     public int removePalindromeSub(String s) {
3         return s.isEmpty() ? 0 : (s.equals(new StringBuilder(s).reverse().toString()) ? 1 : 2);
4     }
5 }

 

LeetCode 题目总结

posted @ 2021-03-09 14:45  CNoodle  阅读(241)  评论(0编辑  收藏  举报