题目 : BeautifulString
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
We say a stringis beautiful if it has the equal amount of 3 or more continuous letters (inincreasing order.)
Here are someexample of valid beautiful strings: "abc", "cde","aabbcc", "aaabbbccc".
Here are someexample of invalid beautiful strings: "abd", "cba","aabbc", "zab".
Given a stringof alphabets containing only lowercase alphabets (a-z), output "YES"if the string contains a beautiful sub-string, otherwise output "NO".
输入
The first linecontains an integer number between 1 and 10, indicating how many test cases arefollowed.
For each testcase: First line is the number of letters in the string; Second line is thestring. String length is less than 10MB.
输出
For each testcase, output a single line "YES"/"NO" to tell if the stringcontains a beautiful sub-string.
提示
Huge input. SlowIO method such as Scanner in Java may get TLE.
样例输入
4
3
abc
4
aaab
6
abccde
3
abb
样例输出
YES
NO
YES
NO
我提交并AC的解答为:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int i;
int T;
int N;
scanf("%d",&T);
while(T--)
{
scanf("%d",&N);
getchar();
int cnt[3], loc = 0;
char ch, pre = ‘\0‘;
bool flag = false;
//memset(cnt,0,sizeof(cnt));
for(i = 0; i < N; i++)
{
scanf("%c", &ch);
//if(ch < ‘a‘ || ch > ‘z‘) { i--; continue; }
if(flag) { continue; }
if(ch == pre){ cnt[loc]++; }
else{
if(loc == 2 && cnt[0] >= cnt[1] && cnt[2] >= cnt[1]){
flag = true;
continue;
}
else if(loc == 2 && (pre + 1 == ch)){
cnt[0] = cnt[1], cnt[1] = cnt[2];
cnt[2] = 1;
}
else if(pre + 1 == ch){
cnt[++loc] = 1;
}
else{
loc = 0;
cnt[loc] = 1;
}
pre = ch;
}
}
if(loc == 2 && cnt[0] >= cnt[1] && cnt[2] >= cnt[1]) { flag = true; }
if(flag) { printf("YES\n"); }
else { printf("NO\n"); }
}//end while
return 0;
}
基本思路是:要满足形成beautiful string,必须由连续的三个字母组成,且中间字母的数量要小于前后字母的数量,所以只要找出这个组合就行了。