LeetCode 1332 Remove Palindromic Subsequences (Python)

Posted by 小明MaxMing on March 8, 2021

题目

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.

解题思路

如果是回文字符串答案是1,如果不是,先删除所有a再删除所有b,答案是2

代码

class Solution:
    def removePalindromeSub(self, s: str) -> int:
        if not s:
            return 0
        l = len(s)
        for i in range(l // 2):
            if s[i] != s[-i - 1]:
                return 2
        return 1

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅