题目如下:

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_kis 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

解题思路:本题不算太难,我的方法是贪心算法+双指针。首先引入head和tail两个变量,分别等于text[0]和text[-1]。如果head等于tail,表示这两者可以组成回文段的两部分,再令head等于text[1],tail等于text[-2];如果两者不相等,令head = head + text[0],tail = text[-2] + tail,直到head 等于tail为止。原则就是每遇到head等于tail的情况,表示这两段是回文段的一部分,重置head 和tail的值。

代码如下:

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

最新文章

  1. tp文件上传;org/RBAC.class.php 权限类;think/page,class,php分页类;
  2. bitmap的图像像素遍历方法
  3. Android逆向工程初步(一) 15.4.24
  4. UVALive 7040 Color (容斥原理+逆元+组合数+费马小定理+快速幂)
  5. windows下如何修改远程登录端口
  6. 如何在jmeter中调用自己写的java工具包
  7. 蓝牙代理报错:invalid handle error
  8. destoon控制标题长度,title中显示全标题 标题字符长度怎么控制?
  9. 给Eclipse安装Google app engine插件
  10. 【HDU1198】Farm Irrigation(回溯+记忆化搜索)
  11. jQuery extend函数详解
  12. 零碎的JS基础
  13. WEB相关系列
  14. HTML 字符集
  15. python 去重方法
  16. 网络编程-Python高级语法-property属性
  17. Java之判断大整数是否为平方数
  18. bus实现兄弟组件传值
  19. 试水STF(smartphone test farm)
  20. 如何同时修改SharePoint帐号和AD帐号的密码 - 批量修改SharePoint Managed Account

热门文章

  1. Hibernate API的使用(Query、Criteria、SQLQuery对象)
  2. 应用安全 - 编程语言漏洞 - PHP语言漏洞汇总
  3. 【Linux开发】Linux磁盘管理
  4. Git 创建分支并合并主分支
  5. django 的 三个 时间 字段
  6. 第五周学习总结&amp;第三次实验报告(String类的应用)
  7. UrlConnection发送http请求 中文乱码解决
  8. kubeadm搭建K8s集群及Pod初体验
  9. (3.4)常用知识-char与varchar的选择
  10. JZOJ2678 树B