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? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true
栈使用
/** * 使用栈 */ var isValid = function(s) { // #1 设置栈 和 map const stack = []; const map = { '[' : ']', '{' : '}', '(' : ')' }; // #2 遍历字符串 for (let i = 0; i < s.length; i++) { // #3 取出当前字符 let chat = s[i]; // #4 判断栈是否为空 if (!stack.length) { // #5 栈为空时,判断是否为左边符号,不是,则返回false if (map[chat]) stack.push(chat); else return false; } else { // #6 取出栈顶元素 let left = stack[stack.length - 1]; // #7 比较 栈顶元素 和 字符 是否相等,相等,栈推出一位;否则判断是否为左边元素;否则返回false if (map[left] === chat) { stack.pop(); } else if (map[chat]) { stack.push(chat); } else { return false; } } } // #8 判断栈是否为空 return !stack.length; };
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: