Sponsored
Sponsored
If the input string is already a palindrome, then we can remove it in one step. If not, since the string contains only 'a' and 'b', we can always remove all 'a's in one step and all 'b's in another step, making at most two steps. Hence, the minimum number of steps to make the string empty is either 1 (if the string is a palindrome) or 2.
Time Complexity: O(n), where n is the length of string s, as we need to potentially traverse the whole string to check if it's a palindrome.
Space Complexity: O(1), as we use only a few extra variables.
1#include <string>
2
3class Solution {
4public:
5 int removePalindromeSub(std::string s) {
6 return std::string(s.rbegin(), s.rend()) == s ? 1 : 2;
7 }
8};
This solution creates a reversed version of the string using reverse iterators and compares it with the original string to check if it is a palindrome. If it is, we return 1; otherwise, we return 2.
The second approach is based on the observation that the given string only consists of 'a' and 'b'. We can count the unique characters in the string. If the string is non-empty, it will always contain either 'a's or 'b's or both. If it contains both, removing all of one type and then the other would take two steps.
Time Complexity: O(n).
Space Complexity: O(1).
1 public int RemovePalindromeSub(string s) {
if (string.IsNullOrEmpty(s)) return 0;
bool hasA = s.Contains('a');
bool hasB = s.Contains('b');
return hasA && hasB ? 2 : 1;
}
}
The C# function checks for both character presence using Contains
and returns the respective minimal steps required.