Valid Parentheses --括号匹配

来源:互联网 发布:阿里域名价格 编辑:程序博客网 时间:2024/06/05 04:16

问题:链接

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解答:

括号匹配,用栈。

需要注意的地方,如果栈为空 压栈,如果栈不为空,比较栈顶元素,匹配退栈,不匹配压栈。


代码:

class Solution {public:    bool isValid(string s) {        stack<char> st;        for(int i = 0; i < s.length(); ++i)        {if(st.empty())st.push(s[i]);            else if((st.top() == '[' && s[i] == ']') || (st.top() == '{' && s[i] == '}') || (st.top() == '(' && s[i] == ')'))                st.pop();            else                st.push(s[i]);        }        if(st.empty())            return true;        return false;    }};


0 0
原创粉丝点击