1. 程式人生 > >leetcode 647. Palindromic Substrings 迴文子串的數量 + 動態規劃DP

leetcode 647. Palindromic Substrings 迴文子串的數量 + 動態規劃DP

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.

程式碼如下:

#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; } };