您的位置:首页 > 其它

Leetcode Longest palindrome substring

2015-06-17 09:08 357 查看

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.

一个palindrome可以用
if odd, mid加长度表示
if even, mid, mid+1 加长度

public class Solution {
public String longestPalindrome(String s) {
if(s.length()<=1)return s;
String r="";
int max=1;
for(int i=0;i<s.length()-1;i++)
{
int t=palindrome(s,i,i);
if(t>max)
{
max=t;
int offset=(t-1)/2;
r=s.substring(i-offset, i+offset+1);
}
t=palindrome(s,i,i+1);
if(t>max)
{
max=t;
int offset=(t-2)/2;
r=s.substring(i-offset,i+offset+2);
}
}
return r;
}

int palindrome(String s, int p1, int p2)
{
while(p1>=0 && p2<s.length() && s.charAt(p1)==s.charAt(p2))
{
p1--;
p2++;
}
return p2-p1-1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: