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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章