1332. Remove Palindromic Subsequences
Description
You are 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. Note that a subsequence does not necessarily need to be contiguous.
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: s is already a palindrome, so its entirety can be removed in a single step.
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”.
Constraints:
- 1 <= s.length <= 1000
s[i]is either'a'or'b'.
💡 Hint 1:
Use the fact that string contains only 2 characters.
💡 Hint 2:
Are subsequences composed of only one type of letter always palindrome strings?
Submitted Code
class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == "": # empty
return 0
if s == s[::-1]: # already a palindrome
return 1
return 2
Runtime: 0 ms | Beats 100.00%
Memory: 19.28 MB | Beats 70.00%
제시된 예시 때문에 무조건 연속된 문자열만 제거해야 한다고 착각해서 헤멨는데, 사실 원하는 문자들만 골라서 회문으로 만들 수 있으면 되는 문제였다. ‘a’의 전부 또는 ‘b’의 전부는 항상 회문이기 때문에 답은 항상 0, 1, 2 중 하나가 된다.
Other Solutions
1st
class Solution:
def removePalindromeSub(self, s):
return 2 - (s == s[::-1]) - (s == "")
time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)