【Leetcode】Longest Palindrome

来源:互联网 发布:centos selinux 开启 编辑:程序博客网 时间:2024/04/30 11:35

【题目】

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(N2)时间O(1)空间的算法。

回文的特点,就是中心对称。对于有N个字符的字符串S,只有2N-1个中心。

为何是2N-1?因为两个字符之间的空档也可以是一个中心。例如”abba”的两个b中间就是一个中心。

围绕一个中心检测回文需要O(N)时间,所以总的时间复杂度是O(N2)。



【代码】

public class Solution {    public String longestPalindrome(String s) {        int start = 0 , end = 0;        for(int i = 0 ; i < s.length();i++){            int len1 = setCenter(s,i,i);            int len2 = setCenter(s,i,i+1);            int max = Math.max(len1,len2);            if(max > end - start){                start = i - (max - 1)/2;                end = i + max/2;            }                    }        return s.substring(start,end + 1);            }        private int setCenter(String s, int left, int right){        while(left >= 0 && right<s.length() && s.charAt(left) == s.charAt(right)){            left--;            right++;        }        return right - left - 1;    }}


0 0
原创粉丝点击