Longest Palindromic Substring

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);

    }

}

 

你可能感兴趣的:(substring)