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".

Constraints:

  • 1 <= s.length <= 1000
  • s[i] is either 'a' or 'b'.

Solution

Time complexity : O(n)
Space complexity : O(1)

class Solution {
public:
    int removePalindromeSub(string s) {
        if (s.empty()) return 0;
        else if (isPalindrome(s)) return 1;
        else return 2;
    }
    
    bool isPalindrome(string &s) {
        int i = 0, j = s.length()-1;
        while (i < j) {
            if (s[i] != s[j])
                return false;
            ++i;
            --j;
        }
        return true;
    }
};

這題是陷阱題。
因為刪除時要找的是 subsequence,不是 substring。

下面是 subsequence 與 substring 的不同:

  1. subsequence 是按照原字順序,可隔間取字的。
  2. substring 就是其必須是原字串的一部份。

ex: computer
subsequence 可以是:cut, our, mur, …
substring 可以是:com, put, ter, mpu, …

因此解法為:

  1. 若 s 為空,則不用刪除 palindrome subseqence。
  2. 若 s 為 palindrome, 則可以直接 1 步將 s 整個刪除。
  3. 若 s 不為 palindrome,則第 1 步將所有 a 刪掉 (只有一種字母的字串都是 palindrome),第 2 步將所有 b 刪掉。