# Palindrome substring

Keywords: Python

## Palindrome substring

#### describe

Given a string, your task is to calculate how many palindrome substrings are in the string.
A substring with different start or end positions is counted as a different substring, even if it is composed of the same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: three palindrome substrings: "a", "b", "c"

Example 2:

Type: "aaa"
Output: 6
Description: Six palindrome substrings: "a", "a", "a", "aa", "aa", "aaa"

Be careful:
The length of the input string will not exceed 1000.

#### thought

In fact, this question is similar to the longest palindrome substring before, so the idea of dp is very simple, so we will not talk about it here.
In addition, you can't help Tucao c++, we must pay attention to the use of c++ built-in functions of length, it is best not to use directly, but to re int a variable storage.
Because most of the built-in function types related to length are unsigned, if you directly use the built-in function related to length to perform operations directly, sometimes there will be some unexpected errors

#### python code

```class Solution:
def countSubstrings(self, s: str) -> int:
dp = [[0 for i in range(len(s))] for i in range(len(s))]            # Initialize dp array
for i in range(len(s)): dp[i][i] = 1                                # Initialization string length 1
for i in range(len(s) - 1):                                         # Initialization length 2
if s[i] == s[i + 1]:
dp[i][i + 1] = 1
k = 2
for i in range(len(s) - 2):
for j in range(len(s) - k):
if s[j] == s[j + k] and dp[j + 1][j + k - 1]:
dp[j][j + k] = 1
k += 1
Sum = 0
for temp in dp:
Sum += sum(temp)
return Sum
```

#### c++ code

```class Solution {
public:
int countSubstrings(string s) {
int s_length = s.length();                                         //Length must be obtained separately because s.length() is of type unsigned
vector<vector<int>> dp(s_length, vector<int>(s_length));            //Initialize dp array
for(int i = 0; i < s_length; i++)
dp[i][i] = 1;                                                   //Character itself must be palindrome
for(int i = 0; i < s_length - 1; i++)
if(s[i] == s[i + 1])
dp[i][i + 1] = 1;                                           //Initializing string palindrome with length 2
int k = 2;                                                          //Interval number of initial test
for(int i = 0; i < s_length; i++){                                  //s.length() - 2 kinds of substrings are left
for(int j = 0; j < s_length - k; j++)
if(s[j] == s[j + k] && dp[j + 1][j + k - 1])
dp[j][j + k] = 1;
k++;
}
int sum = 0;
for(vector<int> temp: dp)
for(int figure: temp)
sum += figure;
return sum;
}
};
```

Posted by sowmithrii on Sat, 07 Dec 2019 17:10:04 -0800