File tree Expand file tree Collapse file tree 2 files changed +104
-0
lines changed Expand file tree Collapse file tree 2 files changed +104
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @Author: Chacha
3
+ * @Date: 2022-03-31 21:48:11
4
+ * @Last Modified by: Chacha
5
+ * @Last Modified time: 2022-03-31 22:40:30
6
+ */
7
+
8
+ /* *
9
+ * 来源:https://leetcode-cn.com/problems/valid-parentheses
10
+ *
11
+ * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
12
+ * 有效字符串需满足:
13
+ * 1. 左括号必须用相同类型的右括号闭合。
14
+ * 2. 左括号必须以正确的顺序闭合。
15
+ *
16
+ * 示例 1:
17
+ * 输入:s = "()"
18
+ * 输出:true
19
+ *
20
+ * 示例 2:
21
+ * 输入:s = "()[]{}"
22
+ * 输出:true
23
+ *
24
+ * 示例 3:
25
+ * 输入:s = "(]"
26
+ * 输出:false
27
+ *
28
+ * 示例 4:
29
+ * 输入:s = "([)]"
30
+ * 输出:false
31
+ *
32
+ * 示例 5:
33
+ * 输入:s = "{[]}"
34
+ * 输出:true
35
+ *
36
+ */
37
+ #include < iostream>
38
+ #include < string>
39
+ #include < stack>
40
+ #include < unordered_map>
41
+
42
+ using namespace std ;
43
+
44
+ class Solution
45
+ {
46
+ private:
47
+ /* data */
48
+ public:
49
+ bool isValid (string s);
50
+ };
51
+
52
+ /* *
53
+ * 判断括号的有效性可以使用「栈」这一数据结构来解决。
54
+ * 栈先入后出特点恰好与本题括号排序特点一致,即若遇到左括号入栈,遇到右括号时将对应栈顶左括号出栈,则遍历完所有括号后 stack 仍然为空
55
+ *
56
+ *
57
+ */
58
+ bool Solution::isValid (string s)
59
+ {
60
+ int n = s.size ();
61
+
62
+ if (n % 2 == 1 )
63
+ {
64
+ return false ;
65
+ }
66
+
67
+ unordered_map<char , char > pairs = {
68
+ {' )' , ' (' },
69
+ {' ]' , ' [' },
70
+ {' }' , ' {' }};
71
+
72
+ stack<char > stk;
73
+
74
+ for (char ch : s)
75
+ {
76
+ if (pairs.count (ch))
77
+ {
78
+ if (stk.empty () || stk.top () != pairs[ch])
79
+ {
80
+ return false ;
81
+ }
82
+ stk.pop ();
83
+ }
84
+ else
85
+ {
86
+ stk.push (ch);
87
+ }
88
+ }
89
+
90
+ return stk.empty ();
91
+ }
92
+
93
+ int main (int argc, char const *argv[])
94
+ {
95
+
96
+ Solution s;
97
+ string str = " ()[]{}" ;
98
+ string str1 = " ([)]" ;
99
+
100
+ cout << " ()[]{} 是否闭合: " << s.isValid (str) << endl;
101
+ cout << " ([)] 是否闭合: " << s.isValid (str1) << endl;
102
+
103
+ return 0 ;
104
+ }
You can’t perform that action at this time.
0 commit comments