LeetCode 题解工作台

删除回文子序列

给你一个字符串 s ,它仅由字母 'a' 和 'b' 组成。每一次删除操作都可以从 s 中删除一个回文 子序列 。 返回删除给定字符串中所有字符(字符串为空)的最小删除次数。 「子序列」定义:如果一个字符串可以通过删除原字符串某些字符而不改变原字符顺序得到,那么这个字符串就是原字符串的一个子序列。 …

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

如果字符串 本身是个回文串,那么只需要删除 次。 如果字符串 不是个回文串,那么先删除所有的 `'a'`,再删除所有的 `'b'`,总共需要删除 次。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

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

 

示例 1:

输入:s = "ababa"
输出:1
解释:字符串本身就是回文序列,只需要删除一次。

示例 2:

输入:s = "abb"
输出:2
解释:"abb" -> "bb" -> "". 
先删除回文子序列 "a",然后再删除 "bb"。

示例 3:

输入:s = "baabb"
输出:2
解释:"baabb" -> "b" -> "". 
先删除回文子序列 "baab",然后再删除 "b"。

 

提示:

  • 1 <= s.length <= 1000
  • s 仅包含字母 'a'  和 'b'
lightbulb

解题思路

方法一:脑筋急转弯

如果字符串 ss 本身是个回文串,那么只需要删除 11 次。

如果字符串 ss 不是个回文串,那么先删除所有的 'a',再删除所有的 'b',总共需要删除 22 次。

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(1)O(1)

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

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate efficiently uses two-pointer scanning to check if the string is a palindrome.

  • question_mark

    The candidate is able to simplify the problem by recognizing the characteristics of the string (only 'a' and 'b').

  • question_mark

    The candidate demonstrates awareness of the optimal number of steps needed based on the structure of the string.

warning

常见陷阱

外企场景
  • error

    Failing to recognize that a string already being a palindrome can reduce the problem to a single step.

  • error

    Overcomplicating the solution by not leveraging the fact that only two characters are involved, leading to inefficient checks.

  • error

    Misunderstanding the requirement to remove subsequences, resulting in an incorrect approach to subsequence deletion.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the string contains more than two distinct characters? The problem would involve different strategies to handle subsequences.

  • arrow_right_alt

    What if the string is initially empty? The answer would trivially be 0 steps.

  • arrow_right_alt

    What if the string contains alternating patterns? The solution might involve a different set of subsequence removals.

help

常见问题

外企场景

删除回文子序列题解:双·指针·invariant | LeetCode #1332 简单