【LeetCode】1332. Remove Palindromic Subsequences
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
定义题,此题需要明确的是Subsequence和Subarray的区别。
Subsequence:子序列,不必连续
{1,2,3,4} 的子序列可以是{1,4},{1,3}.
Subarray:子数列,必须连续
{1,2,3,4}的子数列可以是{1,2},{1,2,3},
因为此题的String是由"a"和"b"组合而成,变可做一下操作:
1.如s为空,返回0
2.若s与其回文相等,返回1
3.先删除s中全部"a",在删除s中全部b,返回2.
class Solution {
public int removePalindromeSub(String s) {
if(s.isEmpty())return 0;
if(s.equals(new StringBuilder(s).reverse().toString())) return 1;
return 2;
}
}