[LeetCode] 647. Palindromic Substrings

来源:互联网 发布:情侣头像 知乎 编辑:程序博客网 时间:2024/05/16 15:35

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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"Output: 6Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:
The input string length won’t exceed 1000.

class Solution {public:    int countSubstrings(string s) {        const int n = s.size();        vector<vector<bool>> dp(n, vector<bool>(n, false));        int cnt = 0;        for (int j = 0; j < n; j++) {            dp[j][j] = true;            cnt++;            for (int i = 0; i < j; i++) {                if (s[i] == s[j] && (i + 1 == j || dp[i + 1][j - 1])) {                    dp[i][j] = true;                    cnt++;                }            }        }        return cnt;    }};