题目链接:https://leetcode.com/problems/longest-palindromic-substring/

题目:Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

解题思路:palindromic-substring是指回文串,例如abba、abcba,它有一个特点就是从字符串的中间开始往两边的字符都是一样的。我们可以从字符串的第二个字符开始向左边和右边同时扫描,找到字符长度最长的回文串。示例代码如下:

public class Solution
{
public String longestPalindrome(String s)
{
int n = s.length();
if (n <= 1)
return s;
int maxlen = 1, k, j, a = 0;
int l;
for (int i = 1; i < n;)
{
k = i - 1;
j = i + 1;
//扫描左边与s[i]相同的字符
while (k >= 0 && s.charAt(k) == s.charAt(i))
k--;
//扫描右边与是s[i]相同的字符
while (j < n && s.charAt(j) == s.charAt(i))
j++;
while (k >= 0 && j < n && s.charAt(k) == s.charAt(j))
{
k--;
j++;
}
l = j - k - 1;
if (maxlen < l)
{
a = k + 1;
maxlen = l;
}
i++;
}
return s.substring(a, a+maxlen);
}

最新文章

  1. Azure媒体服务的Apple FairPlay流功能正式上线
  2. 后端码农谈前端(HTML篇)第一课:HTML概述
  3. HDU3729 I&#39;m Telling the Truth(字典序最大的最大流)
  4. JavaScript 3D图表
  5. selenium文件上传的实现
  6. 让delphi程序不受WINDOWS日期格式的影响
  7. css+js自动化开发之第十五天
  8. javescript扩展方法
  9. LDAP实例异常停止日志提示虚拟内存virtual memory不足
  10. Temporary exceptions can be configured via your app&#39;s Info.plist file.
  11. React-Native集成到已有项目中的总结
  12. &#39;abc&#39; 转换成[a, b, c]一道面试题的思考
  13. Windows平台安装TensorFlow Q&amp;A
  14. Moq 在.net Core 单元测试中的使用
  15. 第十五次oo作业
  16. python: 基本知识(二)
  17. SpringBoot配置属性转载地址
  18. MySQL升级方法一
  19. 即时通讯之smack客户端配置
  20. go_接口

热门文章

  1. C# IEnumerator的使用
  2. 升级win10,提示(RAM)内存不足2G的解决的方法,亲測可行
  3. Scala学习笔记——安装
  4. ubuntu下gedit和vim输入中文和中文显示
  5. Scripting.FileSystemObject对象的详细技巧指南
  6. Struts2+Hibernate+Spring(SSH)三大框架整合jar包
  7. wamp 配置虚拟主机
  8. curl tutorial with examples of usage
  9. libaio.so.1: undefined reference to `__stack_chk_fail@GLIBC_2.4&#39;
  10. 使用intellij idea打包并部署到外部的tomcat