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

Longest Palindromic Substring

时间:2015-01-22 17:24:11      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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.

一种比较朴素的解法,从左至右遍历数组,以当前数字为轴,或者以该数字组成的两个相同数字为轴,(两种情况),向两边扩散。终止条件为,扩散到数组开始或结尾,或者两段元素不一致。记录每种情况的长度,最后返回最长的开始和结束坐标。该解法主要就是注意两种情况。时间复杂度为O(n^2)。

public class Solution {
    public String longestPalindrome(String s) {
        int start = 0;
        int end = 0;
        int maxStart = 0;
        int maxEnd = 0;
        int maxLength = 0;
        //以某数为对称轴
        for(int i = 0; i < s.length(); i++){
            start = i;
            end = i;
            while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
                start--;
                end++;
            }
            start++;
            end--;
            int length = end - start + 1;
            if(length > maxLength){
                maxLength = length;
                maxStart = start;
                maxEnd = end;
            }
        }
        //以某两个对称
        if(s.length() > 1){
            for(int i = 1; i < s.length(); i++){
                if(s.charAt(i) == s.charAt(i - 1)){
                    start = i -1;
                    end = i;
                    while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
                        start--;
                        end++;
                    }
                }
                start++;
                end--;
                int length = end - start + 1;
                if(length > maxLength){
                    maxLength = length;
                    maxStart = start;
                    maxEnd = end;
                }
            }
        }
        return s.substring(maxStart, maxEnd + 1);
    }
}

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4234832.html

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