3
// use to memoize recursive solution7
boundary of both strings,8
l is length of concatenated string,9
ans is used to store final result14
// Longest palindromic string15
int find(string &s, int i, int j) {17
// if left index is greater than right then return20
// if already calculated, return result21
if (v[i][j] != -1) return v[i][j];23
// if we are at stage where i==j,24
// means here single character25
// count it and increase left boundary and decrease right boundary27
return v[i][j] = 1 + find(s, i + 1, j - 1);30
// if two characters are same, count these two and31
// increase left boundary and decrease right boundary34
int k = v[i][j] = 2 + find(s, i + 1, j - 1);38
if left character is from word1 and39
right character is from word240
then store maximum result in ans42
NOTE: till (boundary-1) index s stored word143
and from index (boundary) s stored word246
if (i < boundary && j >= boundary) {52
// if characters are not same,53
// try both increase left index and make right index constent54
// or make left constant or decrease right index55
// and return max of both57
return v[i][j] = max(find(s, i + 1, j), find(s, i, j - 1));61
int longestPalindrome(string word1, string word2) {62
// store boundary of strings63
boundary = word1.size();65
// concatenate both strings68
// find total length of string71
// used to memoize solution72
v = vector<vector<int>>(l + 1, vector<int>(l + 1, -1));75
int k = find(word1, 0, l - 1);