HDU1544(hash)

Palindromes

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1065    Accepted Submission(s): 461


Problem Description
A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.

Now give you a string S, you should count how many palindromes in any consecutive substring of S.
 

Input
There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.

Proceed to the end of file.
 

Output
A single line with the number of palindrome substrings for each case.
 

Sample Input
  
  
aba aa
 

Sample Output
  
  
4 3
 
//首先得压缩,不然肯定在n=5000时超时,压缩后在匹配,注意也是有方法的!

#include<iostream> #include<string.h> using namespace std;

int hash[5005]; char str[5005]; char ts[5005];

int main() {  int i,len,k,count,j,t,temp;  bool flag;  while(scanf("%s",str)!=EOF)  {  // memset(hash,0,sizeof(hash));   len=strlen(str);   hash[0]=1;   ts[0]=str[0];   k=0;   for(i=1;i<len;i++)   {    if(str[i-1]==str[i])    {     hash[k]++;    }    else    {     k++;     hash[k]=1;     ts[k]=str[i];    }   }

  count=0;   for(i=0;i<=k;i++)       count+=(hash[i]+1)*hash[i]/2;

 /*  // 超时  for(i=0;i<=k;i++)   {    for(j=i+1;j<=k;j++)    {     temp=hash[i]<hash[j]?hash[i]:hash[j];     for(t=1;t<=(j-i)/2;t++)     {      if(ts[i+t]==ts[j-t]&&hash[i+t]==hash[j-t])       count+=temp;     }    }   }   */           int l,r;    for(i=0;i<=k;i++)   {    flag=true;    l=i-1;    r=i+1;    if(!(l>=0&&r<=k))     continue;    while(ts[l]==ts[r]&&hash[l]==hash[r])    {     count+=hash[r];     l--;     r++;     if(!(l>=0&&r<=k))     {      flag=false;      break;     }    }    if(flag&&ts[l]==ts[r])     count+=(hash[l]<hash[r]?hash[l]:hash[r]);   }    /*  for(i=0;i<=k;i++)   {    int a=i-1;    int b=i+1;    if(a<0||b>k)     continue;    flag=0;    while(ts[a]==ts[b]&&hash[a]==hash[b])    {     count+=hash[a];     a--;     b++;     if(a<0||b>k)     {      flag=1;      break;     }    }    if(flag==0&&ts[a]==ts[b])    {     count+=hash[a]>hash[b]?hash[b]:hash[a];    }   }*/   //cout<<count<<endl;   printf("%d\n",count);  }  return 0; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值