1332. Remove Palindromic Subsequences

package LeetCode_1332

/**
 * 1332. Remove Palindromic Subsequences
 * https://leetcode.com/problems/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
 * */
class Solution {
    /*
    * solution: check string if Palindromic, if yes, use 1 time, 
    * else because subsequence don't have to be consecutive, and just contains a,b, so can be delete up to 2 times
    * */
    fun removePalindromeSub(s: String): Int {
        var i = 0
        var j = s.length
        while (i < j) {
            if (s[i] != s[j]) {
                //not Palindromic
                return 2
            }
            i++
            j--
        }
        return 1
    }
}

 

posted @ 2020-11-06 11:27  johnny_zhao  阅读(73)  评论(0编辑  收藏  举报