为什么我在 hackerrank 中收到这条消息“~ stdout 上没有响应 ~”?我不知道我错过了什么? 我现在有点沮丧,因为我不知道该怎么做。 所以我只能选择在 Stackoverflow 上发布此查询。
这是我的完整代码:
char* readline();
// Complete the countingValleys function below.
int countingValleys(int n, char* s)
{
int dwnhl = 0, level = 0;
bool frmsurface = true;
int k = strlen(s);
for (int i = 0; i < k; i++)
{
if (level == 0)
{
frmsurface = true;
}
if (s[i] == 'D')
{
level--;
if ((level < 0) && (frmsurface == true))
{
dwnhl++;
frmsurface = false;
//printf("went downhill %d ",i);
}
}
else if (s[i] == 'U')
{ //printf("went uphill %d ",i);
level++;
}
// printf("\nhello - %c",s[i]);
}
printf("\nNumber of downhill = %d \n", dwnhl);
return (dwnhl);
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0')
{
exit(EXIT_FAILURE);
}
char* s = readline();
int result = countingValleys(n, s);
printf("%d\n", result);
return 0;
}
char* readline()
{
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true)
{
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line)
{
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n')
{
break;
}
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data)
{
break;
}
alloc_length = new_length;
}
if (data[data_length - 1] == '\n')
{
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
最佳答案
一个问题是你处理frmsurface
的方式
第一次进入循环时,frmsurface
被设置为 true。如果事件是 UUDD
,您的代码仍会算作一个“山谷”,因为您在上升时没有清除 frmsurface
。
代替
if(level==0)
{
frmsurface=true;
}
你可以试试:
frmsurface = (level == 0);
但我真的不明白你为什么要 bool 值。只需测试 level == 0
即可。像这样的东西:
if(s[i]=='D')
{
if(level==0)
{
dwnhl++;
}
level--;
}
else if (s[i]=='U')
{
level++;
}
另外我想知道这一行是否:
printf("\nNumber of downhill = %d \n", dwnhl);
必须删除。
注意
int k=strlen(s);
for(int i=0;i<k;i++)
可能只是
for(int i=0;i<n;i++)
^
作为 n
传递给函数
关于c - 为什么我会在 hackerrank "~ no response on stdout ~"中收到此消息?我不知道我错过了什么>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182031/