回文字符序列——微软编程之美2015资格赛第2题题解

数据范围

1 ≤ T ≤ 30

5
aba
12111112351121
ccccccc

Case #1: 5
Case #2: 277
Case #3: 1333
Case #4: 127
Case #5: 17

 char 后面子串 num res 0 f “” 0 1
string = "f", res = 1

f后面的子串为d，map[0].num=1
 char 后面子串 num res 0 f "d" 1 1 d "" 0 2
string = "fd", res = 2

 char 后面子串 num res 0 f "da" 2 1 d "a" 1 2 a "" 0 3
string = "fda", res = 3

a后面的子串为d，map[2].num=1;
 char 后面子串 num res 0 f "dad" 5 1 d "ad" 2 2 a "d" 1 3 d "" 0 6

 char 后面子串 num res 0 f "dadf" 6 1 d "adf" 3 2 a "df" 2 3 d "f" 1 4 f "" 0 13

 char 后面子串 num res 0 f "dadfa" 10 1 d "adfa" 7 2 a "dfa" 3 3 d "fa" 2 4 f "a" 1 5 a "" 0

f后面子串为a，更新前map[4].num =0; 更新后map[4].num = 1;

d后面子串为fa，更新前map[3].num = 1，此时new=1，更新后map[3].num=2;
a后面子串为dfa，更新前map[2].num=2，此时new=1，更新后map[2].num = 3;

d后面子串为adfa，更新前map[1].num=3，此时new=4，更新后map[1].num = 3 + new =7;
f后面子串为dadfa，更新前map[0].num=6，此时new=4，更新后map[1].num = 6 + new =10;

#include <vector>
#include <iostream>
#include <string>

using namespace std;

struct Node {
int num;
char my_char;
};
int huiWenNum(string s){
vector<Node> vec;
int i,j,res=0, get_sum=0;
for(i=0;i<s.size();i++){
res++;
if(!vec.empty()){
for(j=vec.size()-1;j>=0;j--){
if(vec[j].my_char==s[i]){
res = res+1+vec[j].num;
}
}
}
Node tmp;
tmp.my_char=s[i];
tmp.num=0;
vec.push_back(tmp);

if(vec.size()>1){
get_sum=1;
for(j=vec.size()-2;j>=0;j--){

if(vec[j].my_char!=s[i]){
vec[j].num+=get_sum;
}else{//meet the same char
int tmp_num = vec[j].num;//storage the num for plus
vec[j].num+=get_sum;
get_sum = get_sum+1+tmp_num;//
}
}

/*cout<<"the map is:"<<endl;
for(j=0;j<vec.size();j++){
cout<<vec[j].my_char<<' '<<vec[j].num<<endl;
}*/
}
}
return res%100007;
}

int main()
{
int i,nSample,res;
string s;

cin>>nSample;
for (i=0;i<nSample;i++){
cin>>s;
res = huiWenNum(s);
cout<<"Case #"<<i+1<<": "<<res<<endl;
}
//system("pause");
return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客