题解 | 有效括号序列

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return bool布尔型
 */
#include <stdbool.h>
#include <string.h>
typedef struct{//结构体封装,!!需要传栈地址,支持多个栈,可复用。
    char data[10000];
    int top;
} Stack;

void push(Stack *s,int val){//*s声明s是一个指向stack结构体的指针
    s->data[s->top]=val;//->用于指针(地址)
    s->top++;
}

int isEmpty(Stack *s){
    return s->top==0;//在27行将top置0,top将不可能等于-1
}

bool isValid(char* s ) {
    // write code here
    Stack st;//定义的stack结构体实体变量
    st.top=0;//重置
    if(s==NULL) return true;
    int len=strlen(s);
    for(int i=0;i<len;i++){
        switch (s[i]) {
            case '('://当元素为左括号时入栈,为右括号时与栈顶元素进行比较,相同则将此时的栈顶元素出栈;不相同或此时栈为空时返回false
            case '[':
            case '{':
            push(&st,s[i]);//栈的地址=&栈变量
            break;
            case ')':
                if(isEmpty(&st)||st.data[st.top-1]!='(')//.用于实体变量(具体的对象),直接访问内部成员
                    return false;
                st.top--;
                break;
            case ']':
                if(isEmpty(&st)||st.data[st.top-1]!='[')//第一次入栈,top从0变为1,而栈底从0记起,此时top指向']''}'')'
                    return false;
                st.top--;//出栈
                break;
            case '}':
                if(isEmpty(&st)||st.data[st.top-1]!='{')
                    return false;
                st.top--;
                break;
        }
    }
    return isEmpty(&st);
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务