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.
这道题建议和leetcode 5. Longest Palindromic Substring 最长回文子串的查找 + 按照length做DP 和 leetcode 516. Longest Palindromic Subsequence 最长回文子序列 + DP动态规划 和leetcode 718. Maximum Length of Repeated Subarray 最长公共子串 + 动态规划DP一起学习
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int countSubstrings(string s)
{
int n = s.length();
vector<vector<bool>> dp(n, vector<bool>(n));
for(int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i >= j)
dp[i][j] = true;
else
dp[i][j] = false;
}
}
int count = 0;
for (int len = 1; len <= n; len++)
{
for (int i = 0; i + len < n; i++)
{
int j = i + len;
if (s[i] == s[j])
dp[i][j] = dp[i + 1][j - 1];
else
dp[i][j] = false;
}
}
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
if (dp[i][j] == true)
count++;
}
}
return count;
}
};