1147. Longest Chunked Palindrome Decomposition

87 篇文章 0 订阅
26 篇文章 0 订阅

Return the largest possible k such that there exists a_1, a_2, ..., a_k such that:

  • Each a_i is a non-empty string;
  • Their concatenation a_1 + a_2 + ... + a_k is equal to text;
  • For all 1 <= i <= k,  a_i = a_{k+1 - i}.

 

Example 1:

Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".

Example 2:

Input: text = "merchant"
Output: 1
Explanation: We can split the string on "(merchant)".

Example 3:

Input: text = "antaprezatepzapreanta"
Output: 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".

Example 4:

Input: text = "aaa"
Output: 3
Explanation: We can split the string on "(a)(a)(a)".

 

Constraints:

  • text consists only of lowercase English characters.
  • 1 <= text.length <= 1000

思路:递归+memo,以为要改些成dp形式,没想到A了

class Solution(object):
    def longestDecomposition(self, text):
        """
        :type text: str
        :rtype: int
        """
        memo={}
        def helper(s):
            n=len(s)
            if n<=1: return n
            if s in memo: return memo[s]
            
            res=1
            for i in range(n//2):
                if s[:i+1]==s[-i-1:]:
                    res=max(res,2+helper(s[i+1:len(s)-i-1]))
            
            memo[s]=res
            return res
        
        res=helper(text)
        return res
        
s=Solution()
print(s.longestDecomposition('ghiabcdefhelloadamhelloabcdefghi'))
print(s.longestDecomposition('merchant'))
print(s.longestDecomposition('antaprezatepzapreanta'))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值