LeetCode_20_valid parentheses

leetcode 20 valid parentheses

思想:
方法:栈
当整个字符串都是由{},[],()字符组成时,需要使用栈数据结构来存储。当出现左括号时,就将其入栈;当出现右括号时,需要将栈顶的元素记录并出栈,如果栈顶元素和等待匹配的右括号不匹配,则返回false,表示无效字符串,如果相互匹配的话,则继续进行下一个括号的匹配操作。当所有字符都遍历完成后,如果栈为空,则返回true,表示有效字符串,反之为无效字符串

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        map<char,char> dict;
        dict['}']='{';
        dict[']']='[';
        dict[')']='(';
        for(int i=0;i<s.size();i++){
            if(dict.find(s[i])!=dict.end()){
                char temp;
                if(!st.empty()){//在对stack进行读操作前,必须要判断stack是否为空
                    temp=st.top();
                    st.pop();
                }
                if(temp!=dict[s[i]])
                    return false;
            }
            else
                st.push(s[i]);
        }
        if(st.empty())
            return true;
        else
            return false;
    }
};

猜你喜欢

转载自blog.csdn.net/all_about_WZY/article/details/87978184