We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接
先明确题意,所谓“有效的括号”,不仅要保证左括号的数量和右括号的数量相等,还要保证括号的位置。
显然,有效括号的部分子表达式中也是有效的括号。
有效括号的部分子表达式中也是有效的括号。
我们可以借助栈来解题,栈满足后进先出,这样在遍历的过程中,每次与栈顶的元素相匹配,能够保证是最近出现的元素。
'(' 、'{'、'['
const isValid = function(s) { // 奇数个括号或右括号开头的情况无效 if (s.length % 2 !== 0 || [')', ']', '}'].indexOf(s[0]) !== -1) return false const map = { '(': ')', '[': ']', '{': '}' } const stack = [] for (let i = 0; i < s.length; i++) { if (s[i] === '(' || s[i] === '{' || s[i] === '[') { stack.push(s[i]) } else if(s[i] !== map[stack.pop()]){ return false } } return stack.length === 0 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接
栈
先明确题意,所谓“有效的括号”,不仅要保证左括号的数量和右括号的数量相等,还要保证括号的位置。
显然,
有效括号的部分子表达式中也是有效的括号。
我们可以借助栈来解题,栈满足后进先出,这样在遍历的过程中,每次与栈顶的元素相匹配,能够保证是最近出现的元素。
'(' 、'{'、'['
等左括号则直接入栈。The text was updated successfully, but these errors were encountered: