647. Palindromic Substrings

来源:互联网 发布:linux vi 批量删除 编辑:程序博客网 时间:2024/05/17 05:57
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".
  • 这题比较简单,找出递推公式较为容易。dp[i] = dp[i-1] + (新增的数目).
class Solution {public:    bool isPalindromic(const char * start,const char *end){        while(start <= end){            if((*start) == (*end)){                start++;                end--;            }else{                return false;            }        }        return true;    }    int countSubstrings(string s) {        int n = s.size();        vector<int> dp(n,1);        dp[0] = 1;        const char * start = s.c_str();        for(int i = 1; i < n;++i){            const char * end = start + i;            dp[i] = dp[i-1];            for(int j = 0; j <= i; j++){                if(isPalindromic(start+j,end)){                    dp[i] += 1;                }            }        }        return dp[n-1];    }};
原创粉丝点击