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.
A 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);
}