给定一串括号,编写一个程序来判断它是否有效。
示例-
input : {{{}}}
output: Valid
input : }{}{}{}}
output: Invalid
我用 C 语言编写了以下代码并测试了输出是否正确。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[20];
int i=0;
printf("Enter String: ");
gets(str);
int count = 0;
while (str[i] != '\0')
{
if (str[i] == '}')
count--;
if (str[i] == '{')
count++;
if (count < 0)
{
printf("\nInvalid");
break;
}
i++;
}
if (count == 0)
printf("\nValid");
return 0;
}
此程序不适用于输入为 {{{}}
的情况,我缺少什么条件?
最佳答案
代码应说明最终结果是否不为 0,如 "{"
if (count == 0) {
printf("Valid\n");
} else {
printf("Invalid\n");
}
return 0;
也可以简单地跳出循环。
if (count < 0) {
// printf("\nInvalid");
break;
}
gets()
自 C99 起已被弃用,并从 C
(C11) 中淘汰,请使用 fgets()
。
char str[20];
fgets(str, sizeof str, stdin);
无需读取整个字符串。代码一次可以使用 1 个 char
。
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
if (str[i] == '}')
count--;
if (count < 0) {
break;
}
else if (str[i] == '{')
count++;
}
}
关于c - 编写一个程序来检查给定的输入字符串是否有平衡括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446061/