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
20. 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
示例 1:
输入: "()" 输出: true 示例 2:
输入: "()[]{}" 输出: true 示例 3:
输入: "(]" 输出: false 示例 4:
输入: "([)]" 输出: false 示例 5:
输入: "{[]}" 输出: true
The text was updated successfully, but these errors were encountered:
解题思路:
HashMap
stack
false
var isValid = function (s) { let map = new Map(), stack = []; map.set("(", ")"); map.set("[", "]"); map.set("{", "}"); for (let i = 0; i < s.length; i++) { let item = s[i]; if (map.has(item)) { stack.push(map.get(item)); } else { if (stack.pop() !== item) return false; } } if (stack.length > 0) return false; return true; };
Sorry, something went wrong.
栈stack解
/** * @param {string} s * @return {boolean} */ var isValid = function (s) { const dict = { '(': ')', '[': ']', '{': '}', }; const stack = []; for (let i = 0; i < s.length; i++) { if (dict[s[i]]) { // 存在 入栈 stack.push(s[i]); } else { // 不存在 出栈,判断与 dict key 是否一致 if (s[i] !== dict[stack.pop()]) return false; } } return !stack.length; }
No branches or pull requests
20. 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
The text was updated successfully, but these errors were encountered: