Skip to content

Latest commit

 

History

History
executable file
·
50 lines (39 loc) · 1.21 KB

0647. Palindromic Substrings.md

File metadata and controls

executable file
·
50 lines (39 loc) · 1.21 KB

0647. Palindromic Substrings, medium, , freq: 39%, acceptance: 57.6%

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.

// 108ms, 13%
class Solution {
public:
    int countSubstrings(string s) {
        const int LEN = 1000;
        vector<vector<bool>> dp(LEN, vector<bool>(LEN, false));
        int res = 0;
        for (int len = 1; len <= s.size(); len++) {
            for (int i = 0; i < s.size(); i++) {
                int j = i + len - 1;
                if (j >= s.size()) break;
                if (s[i] == s[j]) {
                    if (j - i > 2) {
                        if (!dp[i+1][j-1])
                            continue;
                    }
                    dp[i][j] = true;
                    res++;
                }
            }
        }
        return res;
    }
};