啊哈算法-括号的验证

栈原理

#include<stdio.h>
int main(){
    char s[100],ch;
    int top=0;
    while((ch=getchar())!='\n'){
        if(top==0) s[++top]=ch;//首个入栈 
        else{
            if(s[top]=='{'){
                if(ch=='}') top--;//if成立就是括号匹配,那么top下降1. 
                else s[++top]=ch;//if不成立就是括号不匹配,那么top++并且存入当前括号. 
            }
            else if(s[top]=='['){
                if(ch==']') top--;
                else s[++top]=ch;
            }
            else if(s[top]=='('){
                if(ch==')') top--;
                else s[++top]=ch;
            }
            
        }
    }
    if(top==0) printf("Yes");
    else printf("No");
    return 0;
} 

 

posted @ 2021-12-12 17:46  m2on  阅读(4)  评论(0编辑  收藏  举报