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

Longest Palindromic Substring

时间:2017-06-29 15:20:16      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:string   ring   div   solution   pre   sem   inpu   rom   public   

 1 public class Solution {
 2     /**
 3      * @param s input string
 4      * @return the longest palindromic substring
 5      */
 6     public static String longestPalindrome(String s) {
 7         if (s == null || s.isEmpty()){
 8             return null;
 9         }
10         int left = 0;
11         int right = 0;
12         int len = s.length();
13         int longest = 0;
14         for (int i = 0; i < len; i++){
15             for (int j = i + 1; j <= len; j++){
16                 String cub = s.substring(i, j);
17                 if (isPalindroma(cub) && cub.length() > longest){
18                     longest = cub.length();
19                     left = i;
20                     right = j;
21                 }
22             }
23         }
24         String result = s.substring(left, right);
25         return  result;
26 
27     }
28     public static boolean isPalindroma(String s){
29         if (s == null || s.isEmpty()){
30             return false;
31         }
32         int len = s.length() - 1;
33         for (int i = 0; i <= len; i++){
34             if (s.charAt(i) != s.charAt(len - i)){
35                 return false;
36             }
37         }
38         return true;
39     }
40 }

 

Longest Palindromic Substring

标签:string   ring   div   solution   pre   sem   inpu   rom   public   

原文地址:http://www.cnblogs.com/CuiHongYu/p/7094349.html

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