Palinwords - UVa 257 哈希

Palinwords

A palindrome is a string of characters which can be read forward and backward and still result in the same word, e.g. `mumdadmum'. So by definition the empty string, all strings containing 1 character, and all strings containing 2 equal characters are palindromes. The length of a palindrome is the number of characters in the palindrome.

palinword is a string of characters that contains at least 2 different palindromes each with a length of at least 3. (Here the position is immaterial: the same palindrome occurring in another position is not considered as different.) Neither of these 2 palindromes may be embedded in the other palindrome (for example the palindrome `mum' is embedded in the palindrome `amuma', and `aaa' is embedded in `aaaa') but they may partially overlap. Also see the examples below.

Your program's task is to copy only the palinwords from the input file to the output file.

Input

The input for your program is a textfile. Each line in this file is empty or consists of one or more words (uppercase letters `A' through `Z' only) separated by one or more spaces (each line in the input file contains at most 255 characters in all).

Output

The output file is a textfile and must have one palinword per line in order of occurrence in the input file.

Sample Input

MOEILIJKHEDEN INVOER
VERNEDEREN
AMUMA AMAMA MUMMUM
AMATRAMA AAAA
ABATRABAR
DUMMY
WORDS

Sample Output

MOEILIJKHEDEN
VERNEDEREN
AMAMA
MUMMUM

题意:如果一个字符串存在至少两个长度不小于3的不同回文串,就输出这个字符串,但是像amuma中和mum,aaaa中和aaa这样的不能算两个。

思路:哈希,只要找长度为3和4的回文即可,注意判重条件。用times避免每次初始化hash数组超时,用set也可以。

AC代码如下:

#include<cstdio>
#include<cstring>
using namespace std;
int ans1,ans2,len,v,pos1,pos2,times=0;
int hash[1000000];
char str[300];
bool solve(){
    times++;
    if(times>=1000000000)
    { times=1;
      memset(hash,0,sizeof(hash));
    }
    int len=strlen(str);
    int ha;
    int pos1,pos2,ans1=0,ans2=0,i,v;
    for(i=1;i<=len-2;i++)
    if(str[i-1]==str[i+1])
   { v=(str[i-1]-'A')*26*26+(str[i]-'A')*26+(str[i+1]-'A');
     if(hash[v]==times)
      continue;
     ans1++;
     hash[v]=times;
     pos1=i;
   }
    if (ans1>1)
        return true;
    for(i=1;i<=len-3;i++)
    { if(str[i-1]==str[i+2] && str[i]==str[i+1])
      { v=(str[i-1]-'A')*26*26*26+(str[i]-'A')*26*26+(str[i+1]-'A')*26+(str[i+2]-'A');
            if(hash[v]==times)
        continue;
       ans2++;
        hash[v]=times;
        pos2=i;
        }
    }
    if(ans2>1)
   return true;
  if (ans1==1 && ans2==1){
    if (pos2<=pos1 && pos1<=pos2+1)
     return false;
    else
    return true;
    }
    return false;
}
int main()
{ while (~scanf("%s",str))
   if (solve())
     printf("%s\n",str);
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值