Return the largest possible k such that there exists a_1, a_2, ..., a_k such that:
- Each
a_iis a non-empty string; - Their concatenation
a_1 + a_2 + ... + a_kis equal totext; - 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:
textconsists only of lowercase English characters.1 <= text.length <= 1000
-----------------------------------------------------------------
DP is the first intuition. Approve the greedy algorithm:
Assume a longer match l_header = l_tail, a shorter match s_header = s_tail.Draw a map, this indicates l_header consists of (s_header, middle, s_header). So greedy algothm is enough:
class Solution:
def longestDecomposition(self, text):
l = len(text)
res = 0
r_text = text[::-1]
cur,r_cur = '',''
for i in range(0,l):
cur = cur+text[i]
r_cur = r_text[i]+r_cur
if (cur == r_cur):
res+=1
cur,r_cur = '',''
return res

本文介绍了一种基于贪婪算法的字符串匹配与分解方法,旨在找到一个字符串的最大可能分解数量,使得分解后的每个部分都能与其逆序部分相等。通过实例演示了如何实现这一算法,并详细解释了其工作原理。
364

被折叠的 条评论
为什么被折叠?



