[2018-12-09] [LeetCode-Week14] 647. Palindromic Substrings 动态规划

https://leetcode.com/problems/palindromic-substrings/


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


先判断长度为 1 和 2 的字符串的回文性。
对于长度在 3 以上的字符串,考虑
s[i] s[i+1] ..... s[i+len-2] s[i+len-1]
如果中间两端的字符 s[i] == s[i+len-1] , 那么当前字符串的回文性取决于中间的字符串。
最后把所有的字符串加起来即可。
循环时按照长度递增的顺序循环


class Solution {
public:
    int ans = 0;
    
    void procAns(int d) {
        ans += d;
    }
    
    int countSubstrings(string s) {
        int n = s.size();
        int d[1005][1005];
        
        for (int i = 0; i < n; i++) {
            procAns(d[i][1] = 1);
        }
        
        for (int i = 0; i < n; i++) {
            if (i + 1 >= n) break;
            procAns(d[i][2] = (s[i] == s[i+1]) ? 1 : 0);
            
        }
        
        for (int len = 3; len <= n; len++) {
            for (int i = 0; i < n; i++) {
                if (i + len -1 >= n) break;
                procAns(d[i][len] = (s[i] == s[i + len - 1]) ? d[i+1][len-2] : 0);
            }
        }
        
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容