算法第11周Palindromic Substrings[medium]

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.


Analysis

本题是返回给定字符串中的回文子串个数。
回文字符串就是从左到右和从右到左都相同的字符串。
我们可以利用动态规划求最长回文子串的方法得到字符串中的回文子串个数。
首先来回忆得到最长回文子串的动态规划。
我们首先声明一个二维的布尔数组,大小为n*n ,p[n][n]
p[i][j]表示子串s[i,j]是否为回文串。

if i >= j p(i,j) = true;
if s[i] = s[j] p[i][j] = p[i+1][j-1]
otherwise p[i][j] = false

在计算过程中要注意p[i][j]的计算顺序,即i,j是如何变化的。
我们是从(i,i)出发依次计算(i,i+1)(i,i+2)…在每一次计算过程中遍历完所有的i;


Solution

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

                } else {
                    p[j][j+i] = false;
                }
                if (p[j][j+i] == true) res++;
            }
        }
        return res+n;
    }
};

Discussion

还有一种做法就是对于字符串中的字符,以她为中心向外扩展,判断其是否为回文串。

int countSubstrings(string s) {
        int res = 0, n = s.length();
        for(int i = 0; i < n; i++){
            for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j];j++)res++; //substring s[i-j, ..., i+j]
            for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++; //substring s[i-1-j, ..., i+j]
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值