ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

1332. Remove Palindromic Subsequences (E)

2021-03-08 19:01:55  阅读:203  来源: 互联网

标签:string Palindromic 删光 Remove subsequence Subsequences Input Example


Remove Palindromic Subsequences (E)

题目

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

Example 4:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 1000
  • s only consists of letters 'a' and 'b'

题意

给定一个只包含'a'和'b'的字符串s,每次可以从s中删去一个回文子序列,问多少次操作后可以删光s。

思路

注意这里的回文子序列不一定需要其中字符在s中是相连的。考虑三种情况:1. s为空,直接返回0;2. s本身是回文串,则可以一次删光;3. s不是回文,则至少需要2次删光,又因为s只包含两种字符,可以第一次删除全'a'子序列,第二次删除全'b'子序列,保证能2次删光s。


代码实现

Java

class Solution {
    public int removePalindromeSub(String s) {
        return s.isEmpty() ? 0 : isPalindrome(s) ? 1 : 2;
    }

    private boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i <= j) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }
}

标签:string,Palindromic,删光,Remove,subsequence,Subsequences,Input,Example
来源: https://www.cnblogs.com/mapoos/p/14501494.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有