leetcode 647. Palindromic Substrings

原题地址

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

题意

找出所有的回文子串(substring)

思路

naive的解法。
dp[i][j]表示区间[i,j]是否为一个回文串。

代码

要注意的一点就是,我自己在解这样的题的时候习惯用1到N,在数组里取值的时候就要-1

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.size();
        bool dp[n + 1][n + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == j) {
                    dp[i][j] = true;
                } else {
                    dp[i][j] = false;
                }
            }
        }
        int count = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                dp[i][j] = true;
                for (int k = 0; i + k <= j - k && i + k <= n && j - k >= 1 ; k++) {
                    if (s[i + k -1] != s[j - k -1]) {
                        dp[i][j] = false;
                    }
                }
                if(dp[i][j]) count++;
            }
        }
        return count+n;
    }
};

你可能感兴趣的:(leetcode 647. Palindromic Substrings)