【20】Valid Parentheses

    xiaoxiao2025-10-13  2

    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.

    用一个栈即可判断。遇到左括号的时候入栈,遇到右括号的时候弹出栈顶的左括号,并看一下是否配对,配对则继续,不配对就直接返回false。最后处理完后看一下栈是否为空,为空则返回true,不为空返回false(这时有一些左括号没有能与之配对的右括号)。 bool isValid(string s) { int n=s.length(); int par[256]; par['(']=-1;par[')']=1; par['[']=-2;par[']']=2; par['{']=-3;par['}']=3; stack<char> st; for(int i=0;i<n;i++){ char c=s[i]; if(par[c]<0)st.push(c); else{ if(st.empty())return false; char b=st.top(); if(par[c]+par[b]!=0)return false; st.pop(); } } if(st.empty())return true; return false; }
    转载请注明原文地址: https://ju.6miu.com/read-1303114.html
    最新回复(0)