题目来源:https://leetcode.com/problems/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.
动态规划,类似于lcs的解法,数组flag[i][j]记录s从i到j是不是回文
首先初始化,i>=j时,flag[i][j]=true,这是因为s[i][i]是单字符的回文,当i>j时,为true,是因为有可能出现flag[2][1]这种情况,比如bcaa,当计算s从2到3的时候,s[2]==s[3],这时就要计算s[2+1] ?= s[3-1],总的来说,当i>j时置为true,就是为了考虑j=i+1这种情况。
接着比较s[i] ?= s[j],如果成立,那么flag[i][j] = flag[i+1][j-1],否则直接flag[i][j]=false
c++代码:
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 int len = s.length(), max = 1, ss = 0, tt = 0; 5 bool flag[len][len]; 6 for (int i = 0; i < len; i++) 7 for (int j = 0; j < len; j++) 8 if (i >= j) 9 flag[i][j] = true; 10 else flag[i][j] = false; 11 for (int j = 1; j < len; j++) 12 for (int i = 0; i < j; i++) 13 { 14 if (s[i] == s[j]) 15 { 16 flag[i][j] = flag[i+1][j-1]; 17 if (flag[i][j] == true && j - i + 1 > max) 18 { 19 max = j - i + 1; 20 ss = i; 21 tt = j; 22 } 23 } 24 else flag[i][j] = false; 25 } 26 return s.substr(ss, max); 27 } 28 };