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".
思路:可以delete panlindrome subsequence, 所以可以全部delete a,然后全部delete b。这样最多就delete2次;
class Solution {
public int removePalindromeSub(String s) {
if(s == null || s.length() == 0) {
return 0;
}
if(ispalindrome(s)) {
return 1;
} else {
return 2;
}
}
private boolean ispalindrome(String str) {
int i = 0; int j = str.length() -1;
while(i < j) {
if(str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}