c - 用c中的堆栈检查字符串中的平衡括号
问题描述
我正在尝试编写一个程序,在其中我用数组实现堆栈并使用它们来检查给定的字符串是否具有平衡括号。
例如。如果输入 '(()){}[()]' ,程序会输出 'Balanced',否则如果输入 '({})[' 程序会输出 'Notbalanced'。
这部分是栈的数组实现。
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
int stack[MAX];
int top=-1;
void push(char val){
if(top==MAX-1){
printf("stack is already full,error\n");
}else{
top++;
stack[top]=val;
}
}
char pop(){
if(top==-1){
printf("not enough elements,error\n");
exit(1);
}else{
top--;
return stack[top];
}
}
这部分是解决问题的常用方法的实现。
int isMatching(char c1, char c2){
if(c1=='{' && c2=='}')
return 1;
else if(c1 =='(' && c2==')')
return 1;
else if(c1=='[' && c2==']')
return 1;
return 0;
}
int isBalanced(char str[]){
int i=0;
while(str[i]!='\0'){
if(str[i]=='{' || str[i]=='[' || str[i]=='('){
push(str[i]);
}
if(str[i]==')' || str[i] == ']' || str[i]=='}'){
if(stack==NULL){
return 0;
}
if(!isMatching(pop(), str[i])){
return 0;
}
}
i++;
}
if(stack==NULL){
return 1; // balanced parenthesis
}else{
return 0; // not balanced parenthesis
}
}
这是用户输入字符串并测试它是否“平衡”的主要功能。
int main(){
char str[MAX];
int flag;
printf("Enter the string with the brackets and etc.\n");
fgets(str, sizeof(str),stdin);
flag=isBalanced(str);
if(flag==1){
printf("Balanced\n");
}
else{
printf("Not balanced\n");
}
return 0;
}
例如,当我输入一个非常简单的示例时,我得到了错误的答案
Enter the string with the brackets and etc.
()
Not balanced
这应该输出“平衡”。我不明白这是怎么发生的。
解决方案
if (stack==NULL)
是这里的问题,堆栈永远不会为NULL。您需要通过验证来检查堆栈中是否仍有元素top > 0
推荐阅读
- java - Firebase 电话身份验证 (Android)
- android - 当 HTTP 为 404 时,Retrofit 2 返回 Null
- python-3.x - Python:pyautogui 鼠标在 Thread 中移动缓慢且不可靠
- google-app-engine - 谷歌云函数来安排数据存储实体的导出
- c++ - CreateDIBSection 为同一图像返回不一致的位图位值
- git - Yocto 后处理功能中的克隆存储库
- powershell - 在 Powershell 中,如何通过将字符串附加到另一个文件的内容来构建文件?
- c++ - 仅在可变参数模板类中调用现有函数
- reactjs - 卸载反应钩子中的循环行为
- azure-devops - 显示来自 Azure Repos(Github Pages 等效项)的前端 UI