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

lintcode-medium-Longest Palindromic Substring

时间:2016-03-29 14:16:56      阅读:156      评论: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".

Challenge

O(n2) time is acceptable. Can you do it in O(n) time.

 

n^2做法:

public class Solution {
    /**
     * @param s input string
     * @return the longest palindromic substring
     */
    public String longestPalindrome(String s) {
        // Write your code here
        if(s == null || s.length() == 0)
            return s;
        
        String result = s.substring(0, 1);
        
        for(int i = 1; i < s.length(); i++){
            int left = i;
            int right = i;
            
            while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
            
            String temp = s.substring(left + 1, right);
            if(temp.length() > result.length())
                result = temp;
        }
        
        for(int i = 0; i < s.length(); i++){
            int left = i;
            int right = i + 1;
            
            while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
            
            String temp = s.substring(left + 1, right);
            if(temp.length() > result.length())
                result = temp;
        }
        
        return result;
    }
}

 

lintcode-medium-Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5332514.html

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