The problem is described in full here - Aaah!.
Input
The input consists of two lines. The first line is the “aaah” Jon Marius is able to say that day. The second line is the “aah” the doctor wants to hear. Only lowercase ’a’ and ’h’ will be used in the input, and each line will contain between 0 and 999 ’a’s, inclusive, followed by a single ’h’.
Output
Output “go” if Jon Marius can go to that doctor, and output “no” otherwise.
Sample Input 1
aaah
aaaaahSample Output1
noSample Input 2
aaah ahSample Output 2
go
My source code for the problem is below. I wrote one of the fast running implementations, but not the best. What changes can I make so as to improve the efficiency of the code?
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX_LEN 1000
#define MAX_INP 2000
//Checks whether the input is in the required format
int isValidInput(char*);
int main(int __argc, char* __argv[]) {
char strJon[MAX_INP], strDoc[MAX_INP];
int resJon, resDoc;
gets(strJon);
gets(strDoc);
resJon = isValidInput(strJon);
if(resJon <= 0) {
printf("no\n");
return 0;
}
resDoc = isValidInput(strDoc);
if(resDoc <= 0) {
printf("no\n");
return 0;
}
if(resDoc > resJon) {
printf("no\n");
return 0;
}
printf("go\n");
return 0;
}
//Checks valid input & returns len
int isValidInput(char* strInp) {
char *str = strInp;
int len = 0;
if(str == NULL) return -1;
//Check if the string either starts with 'a' or 'h'
if(!(str[0] == 'h' || str[0] == 'H') && !(str[0] == 'a' || str[0] == 'A')) return -1;
len = strlen(str);
if((str[0] == 'h' || str[0] == 'H') && len > 1) return -1;
if(str[len - 1] != 'h' && str[len - 1] != 'H') return -1;
if(len > MAX_LEN) return -1;
while(*(str + 1) != NULL) {
if(*str != 'a' && *str != 'A') return -1;
++str;
}
str = NULL;
return len;
}
gets
calls. Those are buffer overflows by definition. \$\endgroup\$ – CodesInChaos Jun 27 '14 at 10:48return (strlen(doc)>strlen(jon)?"no":"go")
? \$\endgroup\$ – Hugo Delsing Jun 27 '14 at 12:20