1229 Problem V- statistics palindromic substring - Getting title - string handling -C ++ to achieve

Question V: Statistics palindrome substring

Time limit: 1 Sec memory limit: 32 MB
submitted: 102 solution: 32

Title Description

You are given a string S, S you calculate the number of consecutive sub-string is a palindrome string.

Entry

Test input comprising a plurality of sets of data. Each input is a non-empty string of not more than 5000.

Export

For each input and output sub-palindromic number string.

Sample input  Copy

by aba by 
aa

Sample output  Copy

4
3

Code

prompt:

  • I originally practices, unilateral expansion, unified parity situation, a large amount of calculation
  • New angles: reduced time complexity and space complexity -> odd and even bit expansion on both sides of the image (to ensure that each traveled are not repeated counts)
  • Another problem-solving point of view: dynamic programming
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int CountSubstrings(string s){
    int n=s.length(),countRes=0;
    for(int i = 0;i < n;i++){
        int begin=i,end=i; //奇数位拓展,起点相同
        while(begin>=0&&end<n){
            if(s[begin]==s[end]){
                countRes++;
                begin--;
                end++;
            }
            else{
                break;
            }
        }
        begin=i;
        end=i+1; //偶数位拓展,起点相隔
        while(begin>=0&&end<n){
            if(s[begin]==s[end]){
                countRes++;
                begin--;
                end++;
            }
            else{
                break;
            }
        }
    }
    return countRes;

}

int main(){
    string s;
    long int num=0;
    while(cin>>s){
        num=CountSubstrings(s);
        cout<<num<<endl;

    }
}

 

Published 20 original articles · won praise 0 · Views 116

Guess you like

Origin blog.csdn.net/weixin_31789689/article/details/104736646