Longest Palindromic Substring--求字符串最长回文子串

来源:互联网 发布:淘宝问卷调查报告 编辑:程序博客网 时间:2024/06/05 03:48

Question: 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"

所谓回文结构即:

a-b-c-b-a   true

a-b-c-a-a   false 

基本的想法是遍历所有的回文的支点范围从第一个字符的字符串的字符串的最后一个字符的。使用StringBuilder来降低空间复杂度。

(考虑偶数与奇数长度的情况--我们也可以在每个字符中间插入特殊字符如# 来保证整个字符串回文子串始终为奇数情况。如#a#b#b#a#)

public class Solution {        public  String longestPalindrome(String s) {StringBuilder longest = new StringBuilder("");    if (s.length() <= 1) return s;        StringBuilder str = new StringBuilder();        for (int i = 0; i < s.length(); i++) {    str.append("#");    str.append(s.charAt(i));    }    str.append("#");    s = str.toString();        for (int i = 0; i < s.length(); i++) {        expand(str.toString(), longest, i, i);     }        s = longest.toString().replaceAll("#", "");    return s;}private static void expand(String s, StringBuilder longest, int i, int j) {    while (i >= 0 && j < s.length()) {        if (s.charAt(i) == s.charAt(j)) {            if (j - i + 1 > longest.length()) {                longest.delete(0, longest.length());                longest.append(s.substring(i, j + 1));            }            i--;            j++;        }        else            break;    }}}






0 0