c - 编写一个程序来检查给定的输入字符串是否有平衡括号

标签 c arrays string character

给定一串括号,编写一个程序来判断它是否有效。

示例-

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/

相关文章:

C# (Unity) 不同托管数组类型之间的快速复制

javascript - 在浏览器中使用什么数据结构来存储和搜索巨大的 JSON/Dict 类型对象

javascript - 使用div contentEditable insideText 和innerHTML 都没有往返于数据库的换行符

c - 缓存的未命中率是否有可能超过 100%

c - 函数 invertNumerSubstrings 不起作用

c - 将指针分配给具有指向其字段的指针的结构

r - 将字符串分成字符

c - 如何解决强化报告中的整数溢出? (C代码)

c - 由于数组,ISO C90 禁止混合声明和代码。我该如何解决?

java - 强制包含引号的句子成为字符串 - Java