有效的括号

/*
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:
    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。
    注意空字符串可被认为是有效字符串。
*/
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include <iostream>
typedef struct Stack{
    int top;
    char index[1000];
};
/*入栈*/
void stack_push(char e,struct Stack *stack){
    stack->top++;
    stack->index[stack->top]=e;
}
/*出栈*/
void stack_pop(struct Stack *stack){
    stack->top--;
}
/*栈顶*/
char stack_top(struct Stack *stack){
    return stack->index[stack->top];
}
/*是否为空*/
bool stack_empty(struct Stack *stack){
    if(stack->top==-1)
        return 1;
    return 0;
}

bool isValid(char * s){
    int i=0;
    char c;
    struct Stack *stack;
    stack=(struct Stack*)malloc(sizeof(struct Stack));
    stack->top=-1;
    if(s==NULL||s[i]=='\0')
        return true;
    while(s[i]!='\0'){
        if(s[i]=='('||s[i]=='{'||s[i]=='['){
            stack_push(s[i],stack);
        }else{
            c=stack_top(stack);
            //printf("%c ",c);
            switch(s[i]){
                case ')':
                    stack_pop(stack);
                    if(c!='(')
                        return false;
                    break;
                case '}':
                    stack_pop(stack);
                    if(c!='{')
                        return false;
                    break;
                case ']':
                    stack_pop(stack);
                    if(c!='[')
                        return false;
                    break;
                default:
                    break;
            }
        }
        i++;
    }
    if(stack_empty(stack))
        return true;
    return false;
}

bool isValid1(char * s){
    int i=0,top=-1;
    char data[100],c;
    if(s==NULL||s[i]=='\0')
        return true;
    while(s[i]!='\0'){
        if(s[i]=='('||s[i]=='{'||s[i]=='['){
            top++;
            data[top]=s[i];
        }else{
            c=data[top];
            //printf("%c ",c);
            switch(s[i]){
                case ')':
                    top--;
                    if(c!='(')
                        return false;
                    break;
                case '}':
                    top--;
                    if(c!='{')
                        return false;
                    break;
                case ']':
                    top--;
                    if(c!='[')
                        return false;
                    break;
                default:
                    break;
            }
        }
        i++;
    }
    if(top==-1)
        return true;
    return false;
}

int main()
{
    char s[6]={'(',')','[',']','{','}'};
    printf("%d\n",isValid(s));
    return 0;
}

 

posted @ 2020-04-03 11:50  dreamy_java  阅读(227)  评论(0编辑  收藏  举报