手头的问题是:打印包含给定k个单词的第一个最短子段,忽略特殊字符,数字和大小写。如果没有找到子段,则应返回“NO SUBSEGMENT FOUND”
示例输入:
This is a test. This is a programming test. This is a programming test in any language.
4
this
a
test
programming
示例输出:
a programming test This
我的8个测试用例正在通过,但有2个未通过。 我没有弄到什么问题。
我也在寻找更多/更好的测试用例。
我的代码在C:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 200000
int main() {
char S[MAX_STRING_LENGTH]; // original string
char *smallCapsStr,*tempStr; //temp strings having only blank space and small letters
int i=0 ; // used in for loop as inc variable
int start, tail,start2=0,tail2=0; // used in storing start and end index "for answer"
int total; // total words to find in substring
char **arr; // array to store words to find
char **temparr ; // temp arr to store words
int ptr[16];
char *temp2; // temp string
int z=0; // variable informing the end of string
int val=0; //counter var
int x=0; //variable informing the start of string
smallCapsStr=(char*)malloc(sizeof(char)*200000);
char c;
//geting string and converting into small caps
do {
c=getchar();
if((c>='A' && c <='Z')||(c>='a' && c<='z')){
S[i]=(char)c;
*(smallCapsStr + i)=tolower(c);
i++;
}
else{
if(S[i-1]!=' ' && i!=0){
S[i]=' ';
*(smallCapsStr + i)=' ';
i++;
}
}
} while (c != '\n');
S[i]='\0';
*(smallCapsStr + i) ='\0';
scanf("%d",&total);
arr = (char ** )malloc(sizeof(char*)*total);
temparr = (char ** )malloc(sizeof(char*)*total);
// getting words to find in arr and temparr
for(i=0;i<total;i++){
arr[i]=(char*)malloc(sizeof(char)*14);
temparr[i]=(char*)malloc(sizeof(char)*14);
scanf("%s",ptr);
strcpy(arr[i],ptr);
strcpy(temparr[i],ptr);
}
tempStr=smallCapsStr;
while(*(tempStr+1)!='\0'){
sscanf(tempStr,"%s",ptr);
for(i=0;i<total;i++){
if(strcmp(ptr,temparr[i]) == 0){
if(x==0){
start = strlen(S)-strlen(tempStr) ;
temp2 = tempStr+strlen(ptr)+1;
}
x++;
temparr[i]="";
break;
}
}
// updating temp string
tempStr=tempStr+strlen(ptr)+1;
//if all words are found
if(x == total){
tail = strlen(S)-strlen(tempStr) -1;
x=0;
val++;
if(z == 0 || ((tail2-start2)>(tail-start)) ){
start2 = start;
tail2 = tail;
}
z++;
for(i=0;i<total;i++){
temparr[i]= arr[i];
}
tempStr=temp2;
if(val==70)
break;
}
}
// putting ans
if(start2 ==0 && tail2 ==0){
printf("NO SUBSEGMENT FOUND");
}
else{
for(i=start2 ; i<=tail2;i++){
printf("%c",S[i]);
}
}
free(temparr);
free(arr);
free(smallCapsStr);
}
这是来自amazon.interviewstreets的问题,其中测试用例对用户不可见。 任何形式的帮助都会很好。