Leetcode 1332. Remove Palindromic Subsequences
Given a string s
consisting only of letters ‘a’ and ‘b’, you can delete any palindromic subsequence from s
. Return the minimum number of steps to make the given string empty.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
A string is called palindromic if it reads the same backward as forward.
s
:
The length of the string can range from 1 to 1000.s
is a palindrome.public class Solution {
public int removePalindromeSub(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
if (isPalindrome(s)) {
return 1;
}
return 2;
}
private boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example usage:
System.out.println(solution.removePalindromeSub("ababa")); // Output: 1
System.out.println(solution.removePalindromeSub("abb")); // Output: 2
System.out.println(solution.removePalindromeSub("baabb")); // Output: 2
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?