Leetcode C++《熱題 Hot 100-69》647. 迴文子串

Leetcode C++《熱題 Hot 100-69》647. 迴文子串

1. 題目

給定一個字符串,你的任務是計算這個字符串中有多少個迴文子串。

具有不同開始位置或結束位置的子串,即使是由相同的字符組成,也會被計爲是不同的子串。

示例 1:

輸入: “abc”
輸出: 3
解釋: 三個迴文子串: “a”, “b”, “c”.
示例 2:

輸入: “aaa”
輸出: 6
說明: 6個迴文子串: “a”, “a”, “a”, “aa”, “aa”, “aaa”.

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindromic-substrings
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

2. 思路

  • dp[j][i] = true , 如果s[i]==s[j] 並且 dp[j+1][i-1] == true

3. 代碼

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.length();
        bool** dp = new bool* [n];
        int res = 0;
		for (int i = 0; i < n; i++)
		{
			dp[i] = new bool[n]; 
		}
        for (int i = 0; i < n; i++) { // [j,i]
            for (int j = i; j>=0; j--) {
                //cout << "str: " << s.substr(j, i-j+1)  << " j:" << j << " i:" << i  << endl;
                if (s[i] == s[j]) {
                    if ((i-j)<2 || dp[j+1][i-1] == true) {
                        dp[j][i] = true;
                        res++;
                    } else
                    dp[j][i] = false;
                } else
                    dp[j][i] = false;
            }
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章