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

5. Longest Palindromic Substring

时间:2016-08-29 09:05:52      阅读:165      评论: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.

 

O(n^2)

 

public class Solution {
    public String longestPalindrome(String s) {
        String maxString = "";
        if(s.isEmpty() || s.length() == 1){
            return s;
        }
        for(int i = 0; i < s.length() -1; i++){
           String cur =  helper(i, i, s);
           if(cur.length() > maxString.length()){
               maxString = cur;
           }
           cur =  helper(i, i+1, s);
           if(cur.length() > maxString.length()){
               maxString = cur;
           }
           
        }
        return maxString;
    }
    public String helper(int left, int right, String s){
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left --;
            right ++;
        }
        return s.substring(left+1, right);
    }
}

  

5. Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/joannacode/p/5816570.html

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