标签:interview 字符串 question 空间 动态
Total Accepted: 49558 Total Submissions: 238911My Submissions
Question Solution
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.
Show Tags
Have you met this question in a real interview?
Yes
No
分析:回文字符串,aabbaac,采用的方法是动态规划,需要额外n^2的存储空间,对每一个元素作扫描,求得结果,思路
shihuiwen[i][j] 等价于 shihuiwen[i+1][j-1] && char[i]==char[j]
public class Solution {
public String longestPalindrome(String s) {
int l=s.length();
if(l==1)
return s;
boolean[][] dp=new boolean[l][l];
int li=0;
int lj=0;
int maxl=1;
for(int k=0;k<l;k++)
{
int j=k;
for(int i=0;i<l-k;i++,j++)
if(i==j)
dp[i][j]=true;
else if(i+1==j)
{
if(s.charAt(i)==s.charAt(j))
{
dp[i][j]=true;
if(j-i+1>maxl)
{
li=i;
lj=j;
maxl=j-i+1;
}
}
else
dp[i][j]=false;
}
else if(dp[i+1][j-1]==false)
dp[i][j]=false;
else
{
if(s.charAt(i)==s.charAt(j))
{
dp[i][j]=true;
if(j-i+1>maxl)
{
li=i;
lj=j;
maxl=j-i+1;
}
}
else
dp[i][j]=false;
}
}
return s.substring(li,lj+1);
}
}
Leetcode#5Longest Palindromic Substring
标签:interview 字符串 question 空间 动态
原文地址:http://7061299.blog.51cto.com/7051299/1652901