Leetcode Algorithms - Dynamic Programming:647. 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:
The input string length won’t exceed 1000.

分析

根据题意可知,每个单独的字符都是回文串。可以这么定义状态转移方程:以该字符为中心向两边展开,如果左边字符与右边字符相同,那么连起来又是一个回文串。
基于这种思想,写出了如下代码:

class Solution {
public:
    int countSubstrings(string s) {
        int count = 0, left, right;
        for (int i = 0; i < s.size(); i++) {
            left = right = i;
            while (left >= 0 && right < s.size() && s[left] == s[right]) {
                count++;
                left--;
                right++;
            }
        }
        return count;
    }
};

但是上面的代码是错误的,对于aaa的输入,它只能找出4种回文串,实际上有6种。这是因为考虑少了一种情况。
回文串的长度可以是奇数,也可以是偶数。上面的代码只考虑到了长度是奇数的情况,需要进行重构。最终代码如下:

class Solution {
public:
    int countSubstrings(string s) {
        count = 0;
        for (int i = 0; i < s.size(); i++) {
            countSubstringsWithCenterInRange(s, i, i);
            countSubstringsWithCenterInRange(s, i, i+1);
        }
        return count;
    }
private:
    int count;

    void countSubstringsWithCenterInRange(string s, int from, int to) {
        while (from >= 0 && to < s.size() && s[from] == s[to]) {
            count++;
            from--;
            to++;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值