标签:substring longest palindromic string
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.
public String longestPalindrome(String s) { String str; if(s==null) return null; if(s.length()<=1) return s; int len=s.length(); int endIndex=len-1; int i=0; int arr1[]=new int[len]; int arr2[]=new int[len]; Arrays.fill(arr1, 0); Arrays.fill(arr2, 0); int start=0,end=0,count=0; for(i=0;i<endIndex;i++) { start=i; end=i+1; count=0; while(s.charAt(start)==s.charAt(end)) { count+=2; start--; end++; if(start<0||end>endIndex) break; } arr1[i]=count; } for(i=1;i<endIndex;i++) { start=i-1; end=i+1; count=1; while(s.charAt(start)==s.charAt(end)) { count+=2; start--; end++; if(start<0||end>endIndex) break; } arr2[i]=count; } int max1=arr1[0],max1Index=0; int max2=arr2[0],max2Index=0; for(i=1;i<len;i++) { if(max1<arr1[i]) { max1=arr1[i]; max1Index=i; } if(max2<arr2[i]) { max2=arr2[i]; max2Index=i; } } if(max1>max2) str=s.substring(max1Index-max1/2+1, max1Index+max1/2+1); else if(max1<max2) str=s.substring(max2Index-max2/2, max2Index+max2/2+1); else { if(max1Index<max2Index) str=s.substring(max1Index-max1/2+1, max1Index+max1/2+1); else str=s.substring(max2Index-max2/2, max2Index+max2/2+1); } return str; }
leetcode_5_Longest Palindromic Substring
标签:substring longest palindromic string
原文地址:http://blog.csdn.net/mnmlist/article/details/43199933