647. Palindromic Substrings

Problem statement

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".

Solution

This is the same problem with 5. Longest Palindromic Substring. We employ DP to solve it.

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

 

posted @ 2017-07-26 03:47  蓝色地中海  阅读(513)  评论(0编辑  收藏  举报