微软2014 算法笔试题目1及答案

题目1 : Beautiful String

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

We say a string is beautiful if it has the equal amount of 3 or more continuous letters (in increasing order.)

Here are some example of valid beautiful strings: "abc", "cde", "aabbcc", "aaabbbccc".

Here are some example of invalid beautiful strings: "abd", "cba", "aabbc", "zab".

Given a string of alphabets containing only lowercase alphabets (a-z), output "YES" if the string contains a beautiful sub-string, otherwise output "NO".

输入

The first line contains an integer number between 1 and 10, indicating how many test cases are followed.

For each test case: First line is the number of letters in the string; Second line is the string. String length is less than 10MB.

输出

For each test case, output a single line "YES"/"NO" to tell if the string contains a beautiful sub-string.

提示

Huge input. Slow IO method such as Scanner in Java may get TLE.

样例输入
4
3
abc
4
aaab
6
abccde
3
abb
样例输出
YES
NO
YES
NO


解析:采用状态机模型


答案

#include <cstdio>
#include <string>
#include <iostream>
using namespace std;

int IsBeautifulString(int num,char* str);


int main(void)
{
int n;
scanf("%d",&n);
int *sample_size=new int[n];
char **sample=new char*[n];


for(int i=0;i<n;i++)
{
scanf("%d",&sample_size[i]);
sample[i]=new char[sample_size[i]];
scanf("%s",sample[i]);
}


for(int i=0;i<n;i++)
{
if(IsBeautifulString(sample_size[i],sample[i])==1)
printf("YES\n");
else
printf("NO\n");
}


delete [] sample_size;
delete [] sample;
return 0;
}



int IsBeautifulString(int num,char* str)
{
int flag=0;


int l[4]={0};
int count=0;
l[count]=1;

for(int i=1;i<num;i++)
{
if(str[i]==str[i-1])
l[count]++;
else if(str[i]==str[i-1]+1)
l[++count]++;
else
{
count=0;
memset(l,0,sizeof(int)*4);
l[count]=1;
continue;
}


if(count==3||i==num-1)
{
if(l[0]>=l[1]&&l[1]<=l[2]&&l[1]>0)
{
flag=1;
break;
}
else
{
count-=1;
l[0]=l[1];
l[1]=l[2];
l[2]=l[3];
}
}

}

return flag;
}




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。