歪门邪道
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
string s;
int main()
{
int times;
int t=1;
cin>>times>>s;
//cout<<times<<" "<<s;
int flag=0;
if(s.size()==0) cout<<"No";
/**
!!! Attention please
if i's range is [0 size),Accepted(10'),
but if range is [0,size-1) ,Wrong (8');
*/
for(int i=0; i<s.size(); i++)
{
if(s[i]==s[i+1])
{
t++;
}
else
{
if(t>=times)
{
cout<<s[i];
flag=1;
break;
}
t=1;
//i++;
}
//cout<<i<<" "<<t<<endl;
}
if(flag==0)cout<<"No";
//cout << "Hello world!" << endl;
return 0;
}
猜想
感觉可以在s最后添加一个特殊字符,防止遍历时越界(懒得试了)
王牌正解
#include<stdio.h>
#include<string.h>
#define N 10005
char S[N];
int main()
{
int k, i;
scanf("%d%s", &k, S);
int n = strlen(S);
int cnt = 0;//times
char ans = 0, last = 0;//ans 储存结果,last 上一个比较字符
for(i = 0; i < n; i++)
{
if(S[i] != last)//不匹配更换比较字符
{
cnt = 0;//times 归0
last = S[i];
}
cnt++;//无论是否匹配,times++,不匹配 是s[i]已经出现了一次,匹配last出现次数加1
if(cnt >= k)//大于k,退出循环
{
ans = S[i];
break;
}
}
if(!ans) printf("No\n");
else printf("%c\n", ans);
return 0;
}