思路:用分割的方法,标记不在字符集的字母的序号。但是我一开始的代码有错误
原始代码:
#include<stdio.h>
#include<string.h>
int main(){
int T;
scanf("%d",&T);
while(T--){
char s1[10005],s2[27];
scanf("%s",s1);
scanf("%s",s2);
char zm[27];
for(int i=0;i<26;i++){
zm[i]='a'+i;
}
//标记
int t[27]={0};
for(int i=0;i<strlen(s2);i++){
for(int j=0;j<26;j++){
if(s2[i]==zm[j]){
t[j]=1;
}
}
}
//找出不在字母集的字母的序号
int cnt=0,xvhao[10005]={0};
for(int i=0;i<strlen(s1);i++){
for(int j=0;j<26;j++){
if(s1[i]==zm[j]&&t[j]==0){
xvhao[cnt]=i;
cnt++;
}
}
}
int end=xvhao[0];
for(int i=1;i<cnt;i++){
int temp=xvhao[i]-xvhao[i-1]-1;
if(temp>end) end=temp;
}
int d=strlen(s1);
if(cnt==0) printf("%d\n",d);
else if(cnt==1){
if(xvhao[0]==0){
int x1=strlen(s1)-1;
printf("%d\n",x1);}
else {
int x=strlen(s1)-cnt-1;
if(cnt>x){
printf("%d\n",cnt);
}
else printf("%d\n",x);
}
}
else
printf("%d\n",end);
}
}
错误在于:
当 cnt == 1 时,原代码逻辑错误,现在统一按照"计算分割点前后及中间子串长度,取最大值"的逻辑处理,不再单独处理 cnt == 1 的情况,使逻辑更清晰且正确。
◦分别计算第一个分割点之前、中间分割点之间、最后一个分割点之后的子串长度,确保所有可能的子串都被考虑到。
AC代码
#include<stdio.h>
#include<string.h>
int main(){
int T;
scanf("%d",&T);
while(T--){
char s1[10005],s2[27];
scanf("%s",s1);
scanf("%s",s2);
char zm[27];
for(int i=0;i<26;i++){
zm[i]='a'+i;
}
// 标记字符集s2中包含的字母
int t[27]={0};
for(int i=0;i<strlen(s2);i++){
for(int j=0;j<26;j++){
if(s2[i]==zm[j]){
t[j]=1;
}
}
}
// 找出s1中不在字符集s2的字母的序号
int cnt=0,xvhao[10005]={0};
for(int i=0;i<strlen(s1);i++){
for(int j=0;j<26;j++){
if(s1[i]==zm[j]&&t[j]==0){
xvhao[cnt]=i;
cnt++;
}
}
}
int max_len = 0;
// 处理没有不在字符集内的字符的情况
if(cnt==0) {
max_len = strlen(s1);
}
// 处理有至少一个不在字符集内的字符的情况
else {
// 计算第一个分割点之前的子串长度
int first_len = xvhao[0] - 0;
max_len = first_len;
// 计算中间分割点之间的子串长度
for(int i=1;i<cnt;i++){
int temp = xvhao[i]-xvhao[i-1]-1;
if(temp>max_len) {
max_len = temp;
}
}
// 计算最后一个分割点之后的子串长度
int last_len = strlen(s1) - 1 - xvhao[cnt - 1];
if(last_len>max_len) {
max_len = last_len;
}
}
printf("%d\n",max_len);
}
return 0;
}
整体思路:(ai生成
◦ 首先标记字符集 s2 中包含的字母。
◦ 然后找出字符串 s1 中所有"不在 s2 字符集内"的字符的位置,这些位置作为分割点。
◦ 最后计算被分割点分割后的各个子串的长度,取最大值作为结果。