提述: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.
写了一个算法,但是复杂度有点高。有时间补上低复杂度的算法。
这是一道求最长回文子串的题。刚开始感觉无从下手,一篇博客下面的评论给了一种思路:遍历字符串,对每一位进行判断是否有回文串出现。出现回文串的情况我分了三种来讨论:1.当前位置跟左边一位是一致的 2.当前位置跟右边一位是一致的 3. 当前位置的左边跟右边是一致的。用一个boolean值记录如果是情况3的话那么这个子串中间会单出一个字符。 剩下的就是王子串的两边递归直至左右两边的字符不相同为止。
代码:
package leetcode;
public class LongestPalin {
public String longestPalindrome(String s) {
char [] ch = s.toCharArray();
int lenArray[] = new int [s.length()];
String [] stringA = new String[s.length()];
//初始化
for(int i=0;i<lenArray.length;i++){
lenArray[i]=0;
}
boolean isOdd=false;
for(int i=1;i<s.length()-1;i++){
//先判断有没有可能
int p1=0;
int p2=0;
if(ch[i-1]==ch[i]){
//左中相同
stringA[i]= String.valueOf(ch[i-1]);
p1= i-2;
p2 =i+1;
while(p1>=0 && p2< ch.length){
if(ch[p1]==ch[p2]){
// lenArray[i]++;
stringA[i]= stringA[i]+String.valueOf(ch[p1]);
p1--;
p2++;
}else break;
}
}
if(ch[i]==ch[i+1]){
//中右相同
stringA[i]= String.valueOf(ch[i]);
p1= i-1;
p2 =i+2;
while(p1>=0 && p2<ch.length){
if(ch[p1]==ch[p2]){
stringA[i]= stringA[i]+String.valueOf(ch[p1]);
p1--;
p2++;
}else {
break;
}
}
}
if(ch[i-1]==ch[i+1]){
//左右开始往下找
isOdd = true;
p1= i-1;
p2 =i+1;
stringA[i]= String.valueOf(ch[i]);
while(p1>=0 && p2< ch.length){
if(ch[p1]==ch[p2]){
stringA[i]= stringA[i]+String.valueOf(ch[p1]);
p1--;
p2++;
}else break;
}
}
}
String tar = "";
for (String string : stringA) {
if (string!= null && tar.length()< string.length()){
tar= string;
}
}
//构造palin
String res="";
if(isOdd){
for(int i=tar.length()-1;i>0;i--){
res= res+String.valueOf(tar.charAt(i));
}
res += tar;
return res;
}
else{
for(int i=tar.length()-1;i>=0;i--){
res= res+String.valueOf(tar.charAt(i));
}
res += tar;
return res;
}
}
public static void main(String args[]){
LongestPalin lp = new LongestPalin();
<pre name="code" class="java"> String str = "abccbasdfsczxvcasdfghjkkjhgfdsazxc";
//String str = "abccbasdfsczxvcasdfghjkkjhgfdsazxc"; //String str ="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; System.out.println( "answer:"+lp.longestPalindrome(str)); }}