1Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 3An input string is valid if: 4 5Open brackets must be closed by the same type of brackets. 6Open brackets must be closed in the correct order. 7Note that an empty string is also considered valid. 8 9Example 1: 10 11Input: "()" 12Output: true 13Example 2: 14 15Input: "()[]{}" 16Output: true 17Example 3: 18 19Input: "(]" 20Output: false 21Example 4: 22 23Input: "([)]" 24Output: false 25Example 5: 26 27Input: "{[]}" 28Output: true
关于这道题的思路,邓俊辉讲的很是好,没有看过的同窗能够看一下, 视频地址。javascript
使用栈,遍历输入字符串php
若是当前字符为左半边括号时,则将其压入栈中java
若是遇到右半边括号时,分类讨论:数组
1)如栈不为空且为对应的左半边括号,则取出栈顶元素,继续循环app
2)若此时栈为空,则直接返回falseide
3)若不为对应的左半边括号,反之返回falsespa
值得注意的是,若是题目要求只有一种括号,那么咱们其实能够使用更简洁,更省内存的方式 - 计数器来进行求解,而
没必要要使用栈。code事实上,这类问题还能够进一步扩展,咱们能够去解析相似HTML等标记语法, 好比视频
栈的基本特色和操做blog
若是你用的是JS没有现成的栈,能够用数组来模拟
入:push 出: pop
入:push 出 shift 就是队列
代码
语言支持:JS,Python
Javascript Code:
1/* 2 * @lc app=leetcode id=20 lang=javascript 3 * 4 * [20] Valid Parentheses 5 * 6 * https://leetcode.com/problems/valid-parentheses/description/ 7 * 8 * algorithms 9 * Easy (35.97%) 10 * Total Accepted: 530.2K 11 * Total Submissions: 1.5M 12 * Testcase Example: '"()"' 13 * 14 * Given a string containing just the characters '(', ')', '{', '}', '[' and 15 * ']', determine if the input string is valid. 16 * 17 * An input string is valid if: 18 * 19 * 20 * Open brackets must be closed by the same type of brackets. 21 * Open brackets must be closed in the correct order. 22 * 23 * 24 * Note that an empty string is also considered valid. 25 * 26 * Example 1: 27 * 28 * 29 * Input: "()" 30 * Output: true 31 * 32 * 33 * Example 2: 34 * 35 * 36 * Input: "()[]{}" 37 * Output: true 38 * 39 * 40 * Example 3: 41 * 42 * 43 * Input: "(]" 44 * Output: false 45 * 46 * 47 * Example 4: 48 * 49 * 50 * Input: "([)]" 51 * Output: false 52 * 53 * 54 * Example 5: 55 * 56 * 57 * Input: "{[]}" 58 * Output: true 59 * 60 * 61 */ 62/** 63 * @param {string} s 64 * @return {boolean} 65 */ 66var isValid = function(s) { 67 let valid = true; 68 const stack = []; 69 const mapper = { 70 '{': "}", 71 "[": "]", 72 "(": ")" 73 } 74 75 for(let i in s) { 76 const v = s[i]; 77 if (['(', '[', '{'].indexOf(v) > -1) { 78 stack.push(v); 79 } else { 80 const peak = stack.pop(); 81 if (v !== mapper[peak]) { 82 return false; 83 } 84 } 85 } 86 87 if (stack.length > 0) return false; 88 89 return valid; 90};
Python Code:
1 class Solution: 2 def isValid(self,s): 3 stack = [] 4 map = { 5 "{":"}", 6 "[":"]", 7 "(":")" 8 } 9 for x in s: 10 if x in map: 11 stack.append(map[x]) 12 else: 13 if len(stack)!=0: 14 top_element = stack.pop() 15 if x != top_element: 16 return False 17 else: 18 continue 19 else: 20 return False 21 return len(stack) == 0
若是让你检查XML标签是否闭合如何检查, 更进一步若是要你实现一个简单的XML的解析器,应该怎么实现?