字符串的分割-回文

一、题目描述

现在给你一个字符串S,请你计算S中有多少连续子串是回文串。
输入
输入包含多组测试数据。每组输入是一个非空字符串,长度不超过5000.
输出
对于每组输入,输出回文子串的个数。
样例输入
aba
样例输出
4
来源/分类
2019中南大学研究生招生夏令营机试题

二、题解

1:递归进行字符串分割
2:然后统计不重复的子串的数量
(最后内存超限,我也是无能为力了)

三、代码

#include <iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
//回溯法
bool IsPalindRome(string str){
    int end=str.length()-1;
    int start=0;
    while(start<end){
        if(str[start]==str[end]){
            start++;
            end--;
        }else{
           return false;
        }
    }
    return true;
}

void partitionCore(string s,vector<vector<string>>& result,vector<string>& path){
    int len=s.size();
    if(len<1){
        result.push_back(path);
    }
    for(int i=0;i<len;i++){
        string str=s.substr(0,i-0+1);
        if(IsPalindRome(str)){
            path.push_back(str);
            partitionCore(s.substr(i+1),result,path);
            path.pop_back();
        }
    }
}

vector<vector<string>> partition(string s) {
    vector<vector<string> > result;
    vector<string> path;
    partitionCore(s,result,path);
    return result;
}

int main()
{
    string s;
    cin>>s;
    vector<vector<string> > re;
    vector<string>fin;
    re=partition(s);
    for(int i=0;i<re.size();i++)
    {
        for(int j=0;j<re[i].size();j++)
        {
            //cout<
            fin.push_back(re[i][j]);
        }
    }
    //cout<
    sort(fin.begin(),fin.end());
    vector<string>::iterator its=fin.end();
    vector<string>::iterator ite;
    ite=unique(fin.begin(),fin.end());
    fin.erase(ite,its);
    cout<<fin.size();


    return 0;
}

你可能感兴趣的:(刷题)