*************
C++
topic: 1312. 让字符串成为回文串的最少插入次数 - 力扣(LeetCode)
*************
A really tough gay.

Thinking of the simmilar ones is my hobby. And here comes

Solve it angin. Another hobby is review the old ones. Do you gays know 'Crime Sense Revisitation' , something like taht: The return of an offender to the scene of the crime is a phenomenon often discussed in criminal psychology and criminology.
let me do it again, kind of forget how to solve it.
The most significant is defining the dp. dp always works. Here dp[s][m] means the string, which starts from s and end wtit m, has the maximun length. The soul of the logic is

And I donot ndrtstand it again. So check this out first.
Define dp. But how?
make an example:
| i | a | p | p | l | e |
| s | 0 | 1 | 2 | 3 | 4 |
dp[i][j] means the string which starts from j and end with i has the length of palindromic sequence.
i = 0, j = 0, dp[0][0] = 1;
i = 1, j = 0, dp[1][0] = 1;
j = 1, dp[1][1] = 1;
i = 2, j = 0, dp[0 ][2] = 2; why ? Cuz I found s[1] == s[2];
j = 1, dp[1][2] = 2;
j = 2, dp[2][2] = 1;
so a spark comes, it cannot count in order, ita should start from the center and count.
I mave up a decision that make the string into vector and initilise the vector elments 1.
Here is the code
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size(); // get the length of the string
vector<vector<int>> dp(n, vector<int>(n, 1)); // initialise the array into elements zero
}
};
after this step, makes the pointer i goes -> right move and pointer j <- left move, and esitimate
s[j] ?= s[i],
if yes, dp[i + 1][j - 1] = dp[i][j] + 2,
if not, dp[i + 1][j - 1] = max{dp[i + 1][j], dp[i][j - 1]}
the code is east to write
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.length();
if (n == 0) return 0;
// 初始化二维数组
vector<vector<int>> dp(n, vector<int>(n, 0));
// 单个字符是回文
for(int i = 0; i < n; i++) {
dp[i][i] = 1;
}
// 按子串长度从小到大计算
for(int length = 2; length <= n; length++) {
for(int i = 0; i < n - length + 1; i++) {
int j = i + length - 1;
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};
to solve the topic 1312. 让字符串成为回文串的最少插入次数 - 力扣(LeetCode), this method doesnot work, have to find another way.
I have a strong memory about a line in a movie called Jurassic Park.

At very begining, I have a thought that finding the longest palindrome, and count the numbers of the string, the number is
dp = number[string] - number[longestPaliindrome],
however I find it works.

the only difference is return.

1629

被折叠的 条评论
为什么被折叠?



