【LeetCode OJ】Longest Palindromic Substring
2024-08-30 16:57:52
题目链接: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);
}
最新文章
- Azure媒体服务的Apple FairPlay流功能正式上线
- 后端码农谈前端(HTML篇)第一课:HTML概述
- HDU3729 I&#39;m Telling the Truth(字典序最大的最大流)
- JavaScript 3D图表
- selenium文件上传的实现
- 让delphi程序不受WINDOWS日期格式的影响
- css+js自动化开发之第十五天
- javescript扩展方法
- LDAP实例异常停止日志提示虚拟内存virtual memory不足
- Temporary exceptions can be configured via your app&#39;s Info.plist file.
- React-Native集成到已有项目中的总结
- &#39;abc&#39; 转换成[a, b, c]一道面试题的思考
- Windows平台安装TensorFlow Q&;A
- Moq 在.net Core 单元测试中的使用
- 第十五次oo作业
- python: 基本知识(二)
- SpringBoot配置属性转载地址
- MySQL升级方法一
- 即时通讯之smack客户端配置
- go_接口
热门文章
- C# IEnumerator的使用
- 升级win10,提示(RAM)内存不足2G的解决的方法,亲測可行
- Scala学习笔记——安装
- ubuntu下gedit和vim输入中文和中文显示
- Scripting.FileSystemObject对象的详细技巧指南
- Struts2+Hibernate+Spring(SSH)三大框架整合jar包
- wamp 配置虚拟主机
- curl tutorial with examples of usage
- libaio.so.1: undefined reference to `__stack_chk_fail@GLIBC_2.4&#39;
- 使用intellij idea打包并部署到外部的tomcat