/* * Copyright,ShanNong Inc,2018 and onwards * * Author:fanghua fan */
package com.fanghua.algorithm.divideandconquer;
/** * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. * <p> * Example: * Input: "babad" * Output: "bab" * <p> * Note: "aba" is also a valid answer. * <p> * Example: * Input: "cbbd" * Output: "bb" */ publicclassSolutionNum5{ /** * 第一式:动态规划解法 * 两层深度遍历,左右两边同时遍历, * 使用二维数组存储各个回文串开始和结束位置, * 找到左右两边字母相同且以及子串回文, * 时间复杂度是O(n^2) * * @param s * @return */ public String longestPalindromeDynamic(String s){ int n = s.length(); String res = null; boolean[][] dp = newboolean[n][n]; for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]); if (dp[i][j] && (res == null || j - i + 1 > res.length())) { res = s.substring(i, j + 1); } } } return res; }
/** * 第二式:中心开花式 * 全遍历一次字符串,以每个字符为中心进行回文判断,直到回文结束为止 * * @param s * @return */ public String longestPalindrome(String s){ int start = 0, end = 0; for (int i = 0; i < s.length(); i++) { int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, i + 1); int len = Math.max(len1, len2); if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); }
privateintexpandAroundCenter(String s, int left, int right){ int L = left, R = right; while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) { L--; R++; } return R - L - 1; }