leetcode 1332. Remove Palindromic Subsequences 详解 python3

一.问题描述

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'

二.解题思路

新鲜出炉的一道题,我是想着把新出的几道easy的题写了然后数medium的,结果一下子又出两道新题,出题速度也太快了吧。

这题审题最重要!

首先区分两个概念:

1.子数组(subarray):需要在原数组中索引连续。

2.子序列(subsquence):不需要在原数组索引连续。

刚拿到题目的时候没注意到是子序列以为是子数组,一看,wc还挺难的。

再想一想,真可是easy难度的题,然后发现是子序列。

然后s只包含a和b那就很简单了。

答案只可能是0,1,2.

0:s为空,返回0.

1:s本身就是回文串。

2.其他情况

为啥说2是最大的操作次数?

第一次把a全删掉,第二次把b全删掉。。。所以最多就2次。所以说还是要注意,是子序列!!!

还好这道题只包含a和b,如果包含>3的字符数,那就比较麻烦了。

时间复杂度:O(N)。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束  或者 leetcode 解题目录 Python3 一步一步持续更新~

三.源码

class Solution:
    def removePalindromeSub(self, s: str) -> int:
        if not s:return 0
        return 1 if s==s[::-1] else 2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值