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

Write a program to check given input string have balance brackets

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

例子-

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] != '[=11=]')
  {
    if (str[i] == '}')
        count--;
    if (str[i] == '{')
        count++;
    if (count < 0)
    {
        printf("\nInvalid");
        break;
    }   
    i++;        
  }
  if (count == 0)
      printf("\nValid");
  return 0;
 }

此程序不适用于输入 {{{}} 的情况,我缺少什么条件?

你不应该使用 gets()gcc 编译器甚至警告它是危险的,因为没有办法防止缓冲区溢出,例如

char str[6];
gets(str);

使用以下输入

iharob

是一个问题,因为 '[=14=]' 终止符或 '\n' 没有空间,而是

fgets(str, sizeof(str), stdin);

对任何输入都是安全的,虽然输入字符串会被裁剪以适应缓冲区,但不会发生缓冲区溢出。

如果最终结果不是 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++;
  } 
}

以前的答案已经涵盖了避免缓冲区溢出和它不起作用的潜在情况——为了提高性能,我会修改 while 循环以避免检查我们知道永远为假的条件。例如除非我们只是减少计数,否则检查计数是否小于 0 是没有意义的;如果字符是右括号,则无需检查左括号:

while (str[i] != '[=10=]')
{
    if (str[i] == '}')
    {
        count--;

        if (count < 0)
        {
            printf("\nInvalid");
            break;
        }
    }
    else if (str[i] == '{')
        count++;

    i++;        
}

您真的不需要一次输入整个字符串,因为您只是按顺序处理字符。因此,您可以避免使用 gets() 等不安全的方法,甚至可以避免使用 fgets().

等安全但复杂的方法

相反,只需使用 getchar() 来读取和处理每个单独的字符 - 这应该会大大简化您需要做的事情。

至于逻辑,你基本上是对的。保持括号级别,该值最初设置为零。然后读取每个字符并按如下操作:

  • 如果是{,就加一级。
  • 如果是},从水平减一,然后检查以确保水平是非负的。如果没有,那么您的右括号太多,您可以退出。
  • 如果是行尾或文件尾,停止处理字符。检查以确保最终级别为零。如果不是,则您还没有关闭所有括号,因此它是无效的。如果水平为零,则一切都是平衡的。
  • 任何其他字符都可以被视为错误。

有关如何实现这一点的示例,请参见下文:

#include <stdio.h>

int main (void) {
    int debug = 0;       // for debugging purposes.
    int ch, level = 0;   // character and current level.

    // Output prompt, read characters while valid.

    printf("Enter string: ");
    while (((ch = getchar()) == '{') && (ch == '}')) {
        // Select based on '{' or '}'.

        if (ch == '{') {
            // Open bracket, just add one.

            ++level;
            if (debug) printf("DEBUG: {:%d\n",level);
        } else {
            // Close bracket, subtract one and check.

            if (--level < 0) {
                puts ("Level has gone below zero.");
                return 1;
            }
            if (debug) printf("DEbug: }:%d ",level);
        }
    }

    // If not endline/endfile, we have invalid character.

    if ((ch != '\n') && (ch != EOF)) {
        puts ("Invalid character in input.");
        return 1;
    }

    // Level should be zero.

    if (level != 0) {
        puts ("Level still positive at end of line.");
        return 1;
    }

    // All checks now passed okay.

    puts ("Input was fine.");
    return 0;
}

我希望你觉得这有用且简单^-^

    #include<iostream>
    #include<string.h>

    using namespace std;

    {
    string mathEx ;

    cout<<"Please Enter math Expression contain ')' , '(' to                                 
    check balance \n"<<"MathExpression = ";
    cin>>mathEx ;
    int i =0 , count = 0 ;
    while (mathEx [i] != '[=10=]'){
    if(mathEx[i]=='('){
        count++;
     }
    if(mathEx[i]==')'){
        count--;
     }
     if(count<0){
        break ;
     }
     i++;
     }
     if(count==0){
      cout<<"True !";
     }
     else {
     cout<<"Invalid !"<<endl;
     }
        return 0;
     }