Leetcode 5. Longest Palindromic Substring
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 5. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
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"
Similar Questions: Shortest Palindrome Palindrome Permutation Palindrome Pairs Longest Palindromic Subsequence Palindromic Substrings
Next challenges:
方法一:O(n)的时间复杂度。
思路:对原字符串运行"马拉车"算法(Manacher\'s Algorithm),找到最长回文子串的中心位置所在,然后向两边扩充还原。
关于Manacher\'s Algorithm的学习资料:
https://segmentfault.com/a/1190000003914228
http://www.cnblogs.com/grandyang/p/4475985.html
代码:
1 public class Solution { 2 public String longestPalindrome(String s) { 3 int maxRight = 0, pos = 0, maxLen = 0, maxPos = 0; 4 String rs = "#"; 5 for(int i = 0; i < s.length(); i++) rs = rs + s.charAt(i) + "#"; 6 int[] RL = new int[rs.length()]; 7 for(int i = 0; i < rs.length(); i++) { 8 if(maxRight > i) RL[i] = Math.min(maxRight - i, RL[2 * pos - i]); 9 while(i - RL[i] - 1>= 0 && i + RL[i] + 1< rs.length() && rs.charAt(i - RL[i] - 1) == rs.charAt(i + RL[i] + 1)) RL[i]++; 10 if(RL[i] + i > maxRight) { 11 pos = i; 12 maxRight = RL[i] + i; 13 } 14 if(maxLen < 2 * RL[i] + 1) { 15 maxLen = 2 * RL[i] + 1; 16 maxPos = i; 17 } 18 } 19 return rs.substring(maxPos - RL[maxPos], maxPos + RL[maxPos] + 1).replace("#",""); 20 } 21 }
方法二:O(n2)的时间复杂度。
思路:dp[i][j]表示s[i,...,j]是否为回文子串。以下2种情况,dp[i][j]为true:
1.j<i+3并且s[i]==s[j]。(这个画图就会明白)
2.j>=i+3并且dp[i+1][j-1]=true。
实现的时候要先保证s[i+1,..,j-1]已经被遍历过。
代码:
1 public class Solution { 2 public String longestPalindrome(String s) { 3 boolean[][] dp = new boolean[s.length()][s.length()]; 4 int maxLen = 0; 5 String rs = ""; 6 for(int j = 0; j < s.length(); j++) { 7 int minI = j; 8 dp[j][j] = true; 9 for(int i = j - 1; i >= 0; i--) { 10 if(s.charAt(i) == s.charAt(j) && (j < i + 3 || dp[i + 1][j - 1])) { 11 dp[i][j] = true; 12 minI = i; 13 }else { 14 dp[i][j] = false; 15 } 16 } 17 if(j - minI + 1 > maxLen) { 18 maxLen = j - minI + 1; 19 rs = s.substring(minI, j + 1); 20 } 21 } 22 return rs; 23 } 24 }
以上是关于Leetcode 5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
leetcode--5. Longest Palindromic Substring
#Leetcode# 5. Longest Palindromic Substring
LeetCode题解 #5 Longest Palindromic Substring
[LeetCode] 5 Longest Palindromic Substring