题目地址
https://leetcode.com/problems/valid-parentheses/description
题目描述
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
思路
关于这道题的思路,邓俊辉讲的非常好,没有看过的同学可以看一下, 视频地址。
使用栈,遍历输入字符串
如果当前字符为左半边括号时,则将其压入栈中
如果遇到右半边括号时,分类讨论:
1)如栈不为空且为对应的左半边括号,则取出栈顶元素,继续循环
2)若此时栈为空,则直接返回false
3)若不为对应的左半边括号,反之返回false
值得注意的是,如果题目要求只有一种括号,那么我们其实可以使用更简洁,更省内存的方式 - 计数器来进行求解,而
事实上,这类问题还可以进一步扩展,我们可以去解析类似HTML等标记语法, 比如
关键点解析
栈的基本特点和操作
如果你用的是JS没有现成的栈,可以用数组来模拟
入: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的解析器,应该怎么实现?