题意分析
注意循环问题,模拟即可。
代码总览
#include<bits/stdc++.h>
using namespace std;
const int nmax = 1000;
char str[nmax<<1];
int main(){
int n;
while(scanf("%d",&n)!=EOF){
scanf("%s",str);
int len = strlen(str);
for(int i = 0;i<len;++i) str[i+len] = str[i];
for(int i = 0;i<len;++i) str[i+len*2] = str[i];
int ans = -1;
for(int i = 0;i<len;++i){
int p = len+i ,t = len,a1 = 0,kind1 = str[len+i];
while(t--){
if(kind1 == 'w' && str[p] != 'w'){
a1++;
kind1 = str[p];
}else if(str[p] == kind1 || str[p] == 'w') a1++;
else break;
p++;
}
int a2 = 0,kind2 = str[len-1+i]; t = len,p = len-1+i;
while(t--){
if(kind2 == 'w' && str[p] != 'w'){
a2++;
kind2 = str[p];
}else if(str[p] == kind2 || str[p] == 'w') a2++;
else break;
p--;
}
if(a1+a2 >len) ans = len;
else ans = max(ans,a1+a2);
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一种解决特定循环字符串匹配问题的算法实现。通过两次字符串复制来模拟循环,然后遍历字符串并计数匹配字符,特别关注 'w' 字符的处理。最终找到最长的有效匹配长度。
&spm=1001.2101.3001.5002&articleId=79521178&d=1&t=3&u=ffeb01b5b31c445f916e4e3c87071cb1)
681

被折叠的 条评论
为什么被折叠?



