Leetcode: 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, and there exists one unique longest palindromic substring.
分析:
这道题跟Longest Valid Parentheses 有类似之处,不同之处在于,valid parentheses每次扩展都是两个字符,而Palindrome可以每次扩展一个字符。在动态规划算法中,valid parentheses可以用一维数组做备忘录,而palindrome需要一个二维数组。本题有时间复杂度O(n), 空间复杂度O(n)的算法,详见leetcode.pdf page65的Manacher's algorithm。此处用的动态规划方法,时间复杂度和空间复杂度均为O(n^2),但用vector做备忘数据结构会超时。代码如下:
class Solution { public: string longestPalindrome(string s) { int n = s.length(); if(n == 0) return ""; bool f[1000][1000]; int start = 0, max_len = 0; for(int j = 0; j < n; j++) for(int i = 0; i <= j; i++){ if(i == j || j - i > 1 && f[i+1][j-1] && s[i] == s[j] || i + 1 == j && s[i] == s[j]){ f[i][j] = true; if(j - i + 1 > max_len){ max_len = j - i + 1; start = i; } }else f[i][j] = false; } return s.substr(start, max_len); } };