647. Palindromic Substrings

本文介绍了一种高效算法来计算给定字符串中所有回文子串的数量。通过从每个字符(及每对相邻字符)出发,向两边扩展并检查是否构成回文,实现了简单而直观的方法。

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

题目:

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.

解答:

这题是求解一段字符串中有多少个回文子序列。对于求回文子序列,我首先想到一般DP方法,但是好像比较复杂。以下是另外一种方法。遍历字符串,以每一个(两个)字符开始向两遍拓展,如果符合回文,计数就加1;若 两段字符不想当或者越界,则停止循环,看下一个字符。
回文子序列长度可以是奇数,也可以是偶数。所以分两种情况分别求解。

class Solution {
public:
    int countSubstrings(string s) {
        int res = 0;
        for (int i = 0; i < s.size(); i++) {
            func(i, i, res, s);  // 子字符串为奇数形式,以s[i]开始拓展
            func(i, i+1, res, s);  // 子字符串为偶数形式,以s[i]s[i+1]开始拓展
        }
        return res;
    }
    void func(int start, int end, int& res, string s) {
        while (start >= 0 && end < s.size() && s[start] == s[end]) {
            res++;
            // 如果仍然未越界且两端字符相等,则继续向两边拓展
            start--;  
            end++;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值