括号匹配问题:判断括号排列是否有序

 C++

bool isValid(string s) {
    stack<char> st;//建立栈,存储左边的括号
    for(char c : s){
        if(c == '('|| c == '{' || c == '['){
            st.push(c);//遍历字符串s中的元素,对左边的括号进行存储
        }else{
            if(st.empty()) return false;//如果栈空,说明无左边括号,错误
            if(c == ')' && st.top() != '(') return false;//出现右符号但栈顶元素不是对应左符号
            if(c == '}' && st.top() != '{') return false;
            if(c == ']' && st.top() != '[') return false;
            st.pop();//每对比完一个,就从栈中退出
        }
    }
    return st.empty();
}

猜你喜欢

转载自blog.csdn.net/theShepherd/article/details/82117203