栈的应用——1. 括号匹配问题

2020-07-07  本文已影响0人  辘轳鹿鹿
image.png

解题心得:

/*
)(rttyy())sss)(
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>




int main(){

    char str[101],ans[101];
    while(scanf("%s",str)!=EOF){

        int i;
        int len=strlen(str),top=0,stackl[101]={0};
        for(i=0;i<len;i++){
            if(str[i]==')'){
                if(top>0){
                    top--;
                    ans[i]=' ';
                }
                else{
                    ans[i]='?';
                }
            }
            else if(str[i]=='('){
                        stackl[top]=i;
                        top++;
                        ans[i]=' ';
                    }
            else{
                    ans[i]=' ';

            }
        }
        while(top!=0){
            top--;
            ans[stackl[top]]='$';
        }
        printf("%s\n",str);
        for(i=0;i<len;i++){
            printf("%c",ans[i]);
        }
        printf("\n");

    }

    return 0;

}


如果觉得有用的话,就点个赞再走吧^_^

上一篇 下一篇

猜你喜欢

热点阅读