Remove Palindromic Subsequences (E)
题目
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'
题意
给定一个只包含'a'和'b'的字符串s,每次可以从s中删去一个回文子序列,问多少次操作后可以删光s。
思路
注意这里的回文子序列不一定需要其中字符在s中是相连的。考虑三种情况:1. s为空,直接返回0;2. s本身是回文串,则可以一次删光;3. s不是回文,则至少需要2次删光,又因为s只包含两种字符,可以第一次删除全'a'子序列,第二次删除全'b'子序列,保证能2次删光s。
代码实现
Java
class Solution {
public int removePalindromeSub(String s) {
return s.isEmpty() ? 0 : isPalindrome(s) ? 1 : 2;
}
private boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s.charAt(i++) != s.charAt(j--)) return false;
}
return true;
}
}