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.

Example

Given the string = "abcdzdcab", return "cdzdc".

 1 public class Solution {
 2     /**
 3      * @param s input string
 4      * @return the longest palindromic substring
 5      */
 6     public String longestPalindrome(String s) {
 7         if (s == null || s.length() == 0) return s;
 8         
 9         String longest = ""; 
10         for (int i = 0; i <= s.length() - 1; i++) {
11             String p1 = getPalindrome(s, i, i);
12             if (p1.length() > longest.length()) {
13                 longest = p1;
14             }
15                  
16             String p2 = getPalindrome(s, i, i+1);
17             if (p2.length() > longest.length()) {
18                 longest = p2;
19             }
20         }
21         return longest;
22     }
23     
24     String getPalindrome(String s, int l, int r) {
25         int n = s.length();
26         while (l >= 0 && r <= n-1 && s.charAt(l) == s.charAt(r)) {
27             l--;
28             r++;
29         }
30         return s.substring(l + 1, r);
31     }
32          
33 }

 

posted @ 2016-07-14 21:58  北叶青藤  阅读(142)  评论(0编辑  收藏  举报