题目
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.
Example 2:
Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.
Note:
The input string length won’t exceed 1000.
思路
用动态规划的思想,p[j][i + j] = j +1>= i + j-1 || p[j + 1][i + j - 1] ? true : false;为是否是回文字符串的关系式。然后枚举所有子串。其中当s[i + j] == s[j]时,p[j][i + j]= p[j + 1][i + j - 1]很容易理解。而 j +1>= i + j-1是为了,当单个字符a,和两个字符aa 时所设置。当然p可以不用二维数组,而是用函数。此时 j>=i+j 时,p(j,i+j)返回true,否则当s[i + j] == s[j],p(j,i+j)=p[j + 1][i + j - 1], 否则p(j,i+j)=false
代码
class Solution {
public:
int countSubstrings(string s) {
if (s == "" || s.size() == 0) {
return 0;
}
const int n = s.size();
int count = 0;
vector<vector<bool>> p(n,vector<bool>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
if (s[i + j] == s[j]) {
p[j][i + j] = j +1>= i + j-1 || p[j + 1][i + j - 1] ? true : false;
}
if (p[j][i + j]) {
count++;
}
}
}
return count;
}
};