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.
time=255ms accepted 暴力遍历
public String longestPalindrome(String s){ String result=null; int length=s.length(); int max=0; if(length==0) return null; else if(length==1) return s; else{ for(int i=1;i<length;i++){ boolean b=false; int k=0; int j=0; for(int m=i-1;m>=0&&m>=i-2;m--){ if(s.charAt(i)==s.charAt(m)){ k=m-1; b=true; j=i+1; while(b&&k>=0&&j<length){ if(s.charAt(j)==s.charAt(k)){ j++; k--; }else b=false; } if(max<j-k-1){ result=s.substring(k+1,j); max=j-k-1; } } } if(j>=length) break; } return result; } }