5. Longest Palindromic Substring

来源:互联网 发布:携程 知乎 亲子园 编辑:程序博客网 时间:2024/06/03 19:54

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

Example:

Input: "cbbd"Output: "bb"

字符串处理的题目,有多种解法,有一种时间复杂度为O(n3)的解法比较直接,即直接从左往右,依次判断以当前字符为首字符的最长对称子串。

下面给出的解法时间复杂度为O(n2),即以选中的字符为中心,向两边展开判断是否是对称子串。通过下列程序可知,程序时间复杂度为2*(1+2+3+...+ n/2),最长依次扫描的位置为输入字符串中间。

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



原创粉丝点击