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.
//Java Program: Longest Palindromic Substring
public class Solution {
public String longestPalindrome(String s) {
//In this program, there is no empty string acturally.
if (s.length()==0) {
return null;
}
String result = s.substring(0, 1);
//Axis of symmetry: i/2.0
for(int i=1,j;i<2*s.length()-2&&(s.length()-1-i/2)*2+1>result.length();++i) {
for(j=0;(i-1)/2-j>=0&&i/2+1+j<s.length();++j) {
if (s.charAt((i-1)/2-j)!=s.charAt(i/2+1+j)) {
break;
}
}
String temp = s.substring((i-1)/2-j+1, i/2+1+j);
if (temp.length()>result.length()) {
result = temp;
}
}
return result;
}
}
No comments:
Post a Comment