leetcode 647. Palindromic Substrings 回文子串的数量 + 动态规划DP
  DDSsGJLL0ZIX 2023年11月02日 65 0


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”.
Note:
The input string length won’t exceed 1000.

这道题建议和leetcode 5. Longest Palindromic Substring 最长回文子串的查找 + 按照length做DP 和 leetcode 516. Longest Palindromic Subsequence 最长回文子序列 + DP动态规划 和leetcode 718. Maximum Length of Repeated Subarray 最长公共子串 + 动态规划DP一起学习

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;


class Solution 
{
public:
    int countSubstrings(string s) 
    {
        int n = s.length();
        vector<vector<bool>> dp(n, vector<bool>(n));
        for(int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (i >= j)
                    dp[i][j] = true;
                else
                    dp[i][j] = false;
            }
        }

        int count = 0;
        for (int len = 1; len <= n; len++)
        {
            for (int i = 0; i + len < n; i++)
            {
                int j = i + len;
                if (s[i] == s[j])
                    dp[i][j] = dp[i + 1][j - 1];
                else
                    dp[i][j] = false;
            }
        }

        for (int i = 0; i < n; i++)
        {
            for (int j = i; j < n; j++)
            {
                if (dp[i][j] == true)
                    count++;
            }
        }
        return count;
    }
};


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  QtpjMRSUUfXb   2023年12月08日   53   0   0 引脚#include看门狗
  tprTMCWDkFAR   2023年12月07日   31   0   0 头文件#include初始化
  QtpjMRSUUfXb   2023年12月06日   62   0   0 卷积#includeCUDA
  XtSxkqspRqdI   2023年11月13日   21   0   0 整除i++
  UYSNSBVoGd8R   2023年12月08日   26   0   0 引脚#include#define
DDSsGJLL0ZIX