一、题目叙述:
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.
二、解题思路:
吼笨呦,刚说leetcode不限时,今天做这道就碰上超时了,而且题意还理解错了。。。酔,这道题!是让求最长回文字串哒,用暴力的方法遍历所有字符串再判断是否是回文复杂度得是N3了,一定会超时,所以用了动态规划(然并卵,我这个题是搜的,抽空补下动态规划)。就是使用一个二维boolean型数组存放路径状况,即当tan[i][j]为true时,表明i到j为回文子串;判断i到j是否为一个回文字串时,需满足sto[i]==sto[j]并且tan[i+1][j-1]==true;由此输出最长的回文字串即可。
这题我提交了好几次,刚开始用动态规划也超时,后来改了改,合并了两个for循环(给tan[][]数组赋初值),结果就过了,说明复杂度这事需要处处留心呵。
三、源源源码:
import java.util.Arrays; public class Solution { public String longestPalindrome(String s) { int n = s.length(); int max = 1; int first = 0; boolean[][] tan = new boolean[n][n]; // Arrays.fill(tan, false); char[] sto = s.toCharArray(); tan[0][0] = true; for (int i = 1; i < n; i++) { tan[i][i] = true; tan[i][i-1] = true; } // for (int i = 0; i < n-1; i++) // if (sto[i] == sto[i+1]) // { // tan[i][i+1] = true; // first = i; // max = 2; // } for (int i = 2; i <= n; i++) for (int j = 0; j <= n-i; j++) { if (sto[j] == sto[j+i-1] && tan[j+1][j+i-2] == true) { tan[j][j+i-1] = true; max = i; first = j; } } char[] mostlong = new char[max]; for (int i = 0; i < max; i++) mostlong[i] = sto[i+first]; String most = new String(mostlong); return most; } public static void main(String args[]) { String a = "bb"; Solution so = new Solution(); System.out.println(so.longestPalindrome(a)); } }