Leetcode 647. Palindromic Substrings

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

题目

class Solution {
public:
    int countSubstrings(string s) {
        n=s.size();
        int sum=0;
        for(int i=0;i<n;++i){
            sum+=count(s,i,i);
            sum+=count(s,i,i+1);
        }
        return sum;
    }
private:
    int n;
    int count(string&s,int l,int r){
        int index=0;
        while(l>=0&&r<n&&s[l]==s[r]){
            --l;
            ++r;
            ++index;
        }
        return index;
    }
};
posted @ 2021-09-07 16:07  飞翔的菜鸟123  阅读(23)  评论(0编辑  收藏  举报