mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 08:27:30 +08:00
81 lines
2.8 KiB
Markdown
81 lines
2.8 KiB
Markdown
# [1332. Remove Palindromic Subsequences](https://leetcode.com/problems/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 中删除一个回文 子序列。返回删除给定字符串中所有字符(字符串为空)的最小删除次数。
|
||
|
||
「子序列」定义:如果一个字符串可以通过删除原字符串某些字符而不改变原字符顺序得到,那么这个字符串就是原字符串的一个子序列。
|
||
|
||
「回文」定义:如果一个字符串向后和向前读是一致的,那么这个字符串就是一个回文。
|
||
|
||
## 解题思路
|
||
|
||
- 笔者读完题以为是第 5 题的加强版。在字符串中每次都找到最长的回文子串删除,一直删除到找不到回文子串结束,删除的总次数 + 剩余字母数 = 最小删除次数。提交以后 `wrong answer` 了,在 `bbaabaaa` 这组测试用例出错了。如果按照找最长回文字符串的思路,先找到最长回文子串 `aabaa`,剩余 `bba`,还需要再删除 2 次,`bb` 和 `a`。总共删除次数是 3 。为什么出错误了呢?仔细再读题,题目中说的是子序列,这不是连续的,再加上这道题是 `easy` 难度,其实很简单。
|
||
- 这道题的答案只可能是 0,1,2 。空串对应的 0 。如果有一个字母,单个字母可以构成回文,所以是 1,如果字符串长度大于等于 2,即 `a` 和 `b` 都有,第一步先删除所有 `a`,因为所有的 `a` 构成了回文子序列。第二步删除所有的 `b`,因为所有的 `b` 构成了回文子序列。经过这样两步,一定能删除所有字符。
|
||
|
||
## 代码
|
||
|
||
```go
|
||
package leetcode
|
||
|
||
func removePalindromeSub(s string) int {
|
||
if len(s) == 0 {
|
||
return 0
|
||
}
|
||
for i := 0; i < len(s)/2; i++ {
|
||
if s[i] != s[len(s)-1-i] {
|
||
return 2
|
||
}
|
||
}
|
||
return 1
|
||
}
|
||
``` |