[leetcode]647. Palindromic Substrings

本文介绍了一种算法,用于计算给定字符串中回文子串的数量。通过三种不同的动态规划方法实现,包括如何判断子串是否为回文以及如何统计不同起始和结束索引的子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/palindromic-substrings/#/description

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:

  1. The input string length won't exceed 1000.

方法一 (dp)

int countSubstrings(string s) {
		if(s.empty())
			return 0;
		if(s.size() == 1)
			return 1;

		int res = 0;

		vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));

		for(int i = s.size() - 1; i>= 0; i--) {
			dp[i][i] = true;
			res++;

			for(int j = i + 1; j < s.size(); j++) {
				if(s[i] == s[j] && (i + 1 == j || dp[i + 1][j - 1])) {
					dp[i][j] = true;
					res++;
				}
			}
		}

		return res;
	}


方法二:(dp)

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.size(), count = 0;
        vector<vector<int>> dp(n, vector<int> (n));
        for ( int end = 0; end < n; ++end ) {
            dp[end][end] = 1;
            ++count;
            for ( int start = 0; start < end; ++start ) {
                if ( s[start] == s[end] && (start+1 >= end-1 || dp[start+1][end-1])) {
                    dp[start][end] = 1;
                    ++count;
                }
            }
        }
        return count;
    }
};

方法三

class Solution {
public:
    int countSubstrings(string s) {
        int res = 0, n = s.length();
        for(int i = 0; i<n ;i++ ){
            // i or (i-1, i) is the middle index of the substring, 2*j + 1 or 2*j + 2 is the length of the substring
            for(int j = 0; i-j >=0 && i+j <n && s[i-j] == s[i+j]; j++)res++;
            for(int j = 0; i-1-j >=0 && i+j <n && s[i-1-j] == s[i+j];j++)res++;
        }
        return res;
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值