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.
Analysis:
Solution:
1: public class Solution {
2: public String longestPalindrome(String s) {
3: if(s==null)
4: return null;
5: if(s.length()==1)
6: return s;
7: String result="";
8: for(int i=0;i<s.length();i++)
9: {
10: String temp1=getPalindrome(s,i,i);
11: if(temp1.length()>=result.length())
12: {
13: result=temp1;
14: }
15: String temp2=getPalindrome(s,i,i+1);
16: if(temp2.length()>=result.length())
17: {
18: result=temp2;
19: }
20: }
21: return result;
22: }
23: private String getPalindrome(String s, int begin, int end)
24: {
25: while(begin>=0&&end<s.length()&&s.charAt(begin)==s.charAt(end))
26: {
27: begin--;
28: end++;
29: }
30: return s.substring(begin+1,end);
31: }
32: }
没有评论:
发表评论