这道题没什么固定算法,关键就是思维是否够缜密。
我的方法是先找出DDE模式(其中D的长度必须大于2),再根据具体的情况进行下一步处理。这个具体情况就是当D>E时,E就是A;当D<E时,把E拆成CD,也就是CAB。大的方向说完了,就是细节问题,当D>E时,E能否和D的前半段匹配,如果可以匹配那么D拆成AB后AB是否符合题目要求,当D<E时,D能否和E的后半段匹配,同样E拆成CAB后是否符合题目要求。
最后感谢一下Kewowlo博客里的数据。
代码(C++):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define MAX 55
using namespace std;
char s[MAX];
int main()
{
//freopen("in.txt","r",stdin);
int t,i,j,k,id,len;
bool flag;
string str,str1,str2,str3;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
str="";
for(i=0;i<strlen(s);i++) //去除标点符号
{
if(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z') str+=s[i];
}
flag=false;
len=str.length();
for(i=1;i<len;i++)
{
if(str[0]==str[i])
{
if(i<2) continue; //如果D的长度小于2,直接跳过
if(i*2-1<len&&str.substr(0,i)==str.substr(i,i)) //判断是否存在DD的情况
{
id=2*i;
if(len-id>i){ //针对ABABCAB模式
for(j=i-1,k=0;j>=0;j--,k++) //判断E的后半段是否有D
{
if(str[len-1-k]!=str[j]) break;
}
if(j<0){
str3=str.substr(id,len-i-id); //判断是否能分成符合条件的ABC,即判断ABC是否不相同且不为空
for(j=1;j<i;j++) //枚举A的长度
{
str1=str.substr(0,j);
str2=str.substr(j,i-j);
if(str1!=str2&&str1!=str3&&str2!=str3) break;
}
if(j<i){
flag=true;
break;
}
}
}else if(len-id<i&&len>id){ //针对ABABA模式
for(j=0;j<len-id;j++) //判断E是否为D的前半段
{
if(str[j]!=str[id+j]) break;
}
if(j==len-id&&str.substr(0,j)!=str.substr(j,i-j)){ //此时E为A,判断是否D所包含的AB不相同
flag=true;
break;
}
}
}
}
}
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}
题目( http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5350):
Poetry is a form of literature that uses aesthetic and rhythmic qualities of language. There are many famous poets in the contemporary era. It is said that a few ACM-ICPC contestants can even write poetic code. Some poems has a strict rhyme scheme like "ABABA" or "ABABCAB". For example, "niconiconi" is composed of a rhyme scheme "ABABA" with A = "ni" and B = "co".
More technically, we call a poem pretty if it can be decomposed into one of the following rhyme scheme: "ABABA" or "ABABCAB". The symbol A, B and C are different continuous non-empty substrings of the poem. By the way, punctuation characters should be ignored when considering the rhyme scheme.
You are given a line of poem, please determine whether it is pretty or not.
Input
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
There is a line of poem S (1 <= length(S) <= 50). S will only contains alphabet characters or punctuation characters.
Output
For each test case, output "Yes" if the poem is pretty, or "No" if not.
Sample Input
3 niconiconi~ pettan,pettan,tsurupettan wafuwafu
Sample Output
Yes Yes No