码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2016-07-15 00:03:09      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5671895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!