[LeetCode] #5 最长回文子串
给你一个字符串 s
,找到 s
中最长的回文子串。
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
暴力法(超时)
class Solution { public String longestPalindrome(String s) { String res = ""; int max = 0; for (int i = 0; i < s.length(); i++) for (int j = i + 1; j <= s.length(); j++) { String t = s.substring(i, j); if (isPalindromic(t) && t.length() > max) { res = s.substring(i, j); max = Math.max(max, res.length()); } } return res; } public boolean isPalindromic(String s) { for (int i = 0; i < s.length() / 2; i++) if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false; return true; } }
动态规划
dp[i][j] 表示 s[i..j] 是否是回文串
状态转移方程:dp[i][j] = dp[i + 1][j - 1]
public class Solution { public String longestPalindrome(String s) { int len = s.length(); if (len < 2) { return s; } int maxLen = 1; int begin = 0; boolean[][] dp = new boolean[len][len]; for (int i = 0; i < len; i++) { dp[i][i] = true; } char[] charArray = s.toCharArray(); for (int L = 2; L <= len; L++) { for (int i = 0; i < len; i++) { int j = L + i - 1; if (j >= len) { break; } if (charArray[i] != charArray[j]) { dp[i][j] = false; } else { if (j - i < 3) { dp[i][j] = true; } else { dp[i][j] = dp[i + 1][j - 1]; } } if (dp[i][j] && j - i + 1 > maxLen) { maxLen = j - i + 1; begin = i; } } } return s.substring(begin, begin + maxLen); } }
中心扩展
从子串为1或2开始不断地向两边扩展。如果两边的字母相同,我们就可以继续扩展;如果两边的字母不同,我们就可以停止扩展,因为在这之后的子串都不能是回文串了。
class Solution { public String longestPalindrome(String s) { if (s == null || s.length() < 1) { return ""; } 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); } public int expandAroundCenter(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { --left; ++right; } return right - left - 1; } }
知识点:无
总结:无