首页 > 代码库 > 微软2014 算法笔试题目1及答案
微软2014 算法笔试题目1及答案
题目1 : Beautiful String
- 样例输入
4 3 abc 4 aaab 6 abccde 3 abb
- 样例输出
YES NO YES NO
描述
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.
解析:采用状态机模型
答案
#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; }
微软2014 算法笔试题目1及答案