Topics are as follows:
Return the largest possible
k
such that there existsa_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 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:
text
consists only of lowercase English characters.1 <= text.length <= 1000
Problem-solving ideas: This title is not too difficult, my approach is a greedy algorithm + dual pointers. First introducing two variables head and tail, respectively, equal to text [0] and text [-1]. If the head is equal to tail, which represents both the part may be composed of two palindromic segment, then make head equal text [1], tail equal text [-2]; if the two are not equal, so that head = head + text [0] , tail = text [-2] + tail, head until it equals the tail. Principle is equal to the tail head encounters each case, which represents a part of two palindromic segment, head and tail of the reset value.
code show as below:
class Solution(object): def longestDecomposition(self, text): """ :type text: str :rtype: int """ res = 0 head_inx = 0 tail_inx = len(text) - 1 head = '' tail = '' while head_inx <= tail_inx and head_inx < len(text) and tail_inx >= 0: if head == '' and tail == '': head = text[head_inx] tail = text[tail_inx] head_inx += 1 tail_inx -= 1 elif head == tail: res += 2 head = text[head_inx] tail = text[tail_inx] head_inx += 1 tail_inx -= 1 else: #head_inx += 1 #tail_inx -= 1 head = head + text[head_inx] tail = text[tail_inx] + tail head_inx += 1 tail_inx -= 1 res += 2 if head == tail and head_inx - len(head) != tail_inx + len(tail) else 1 return res if res != 0 else 1