Catalogue
Description
Thinking
- Plan A (Two-dimensional, from top to bottom)
- State: dp[i][j] denotes whether the substring whose indices from i to j is a palindrom.
- Transformation equation : dp[i][j] = true if dp[i+1][j-1].
- Plan B (One-dimensional, state compression, from bottom to top)
- State: dp[i] denotes whether the substring whose indices from j to i is a palindrom (j = {0…i}).
- Transformation equation : dp[j] = true if dp[j+1]
Code
- Plan A
int countSubstrings(string s) {
int size = s.length();
vector< vector<int> > dp (size, vector<int>(size, 0));
// diagonal
int count = size;
for (int i=0; i<size; i++) {
dp[i][i] = 1;
}
for (int i=size-1; i>=0; i--) {
for (int j=i; j<size; j++) {
if (i != j && s[i] == s[j]) { // s[i] == s[j]
if (i+1 == j || dp[i+1][j-1]) {
dp[i][j] = 1;
count++;
}
}
}
}
return count;
}
Plan B
int countSubstrings(string s) {
int size = s.length();
int* dp = new int[size]();
int count = 0;
for (int i=0; i<size; i++) {
dp[i] = 1;
count++;
for (int j=0; j<i; j++) {
if (s[i] == s[j] && dp[j+1]) {
dp[j] = 1;
count++;
} else {
dp[j] = 0;
}
}
}
return count;
}