Palindromic Substrings

2019-08-07  本文已影响0人  STACK_ZHAO

Discription

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".

C++ code


//Palindromic Substrings
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<stdio.h>
using namespace std;
int countSubstrings(string s){
    int n=s.length(),m=s.length();
    for(int i=0;i<m;i++){
        if(i>0&&s[i]==s[i-1]){
            int p=i-1,q=i;
            while(p>=0&&q<m&&s[p]==s[q]){
                n++;
                p--;
                q++;
            }
        }
        int p=i-1,q=i+1;
        while(p>=0&&q<m&&s[p]==s[q]){
                n++;
                p--;
                q++;
        }
    }
    return n;
}

int main(){
    string s="aaa";
   //cout<<s.substr(0,3);
    int ss=countSubstrings(s);
    cout<<ss<<endl;
    return 0;

}






上一篇 下一篇

猜你喜欢

热点阅读