File tree Expand file tree Collapse file tree 1 file changed +61
-1
lines changed Expand file tree Collapse file tree 1 file changed +61
-1
lines changed Original file line number Diff line number Diff line change @@ -88,7 +88,7 @@ https://leetcode-cn.com/problems/valid-parentheses/description
88
88
89
89
### 代码
90
90
91
- 代码支持:JS,Python
91
+ 代码支持:JS,Python,Java,C++
92
92
93
93
Javascript Code:
94
94
@@ -150,6 +150,66 @@ Python Code:
150
150
return len (stack) == 0
151
151
```
152
152
153
+ Java Code:
154
+
155
+ ``` java
156
+ class Solution {
157
+ public boolean isValid (String s ) {
158
+ // 1.判断空字符串
159
+ if (s. isEmpty()) return true ;
160
+ // 2.创建辅助栈
161
+ Stack<Character > stack = new Stack<> ();
162
+ // 3.仅遍历一次
163
+ for (char c : s. toCharArray()){
164
+ if (c == ' (' ){
165
+ stack. push(' )' );
166
+ }else if (c == ' [' ){
167
+ stack. push(' ]' );
168
+ }else if (c == ' {' ){
169
+ stack. push(' }' );
170
+ }else if (stack. isEmpty() || c != stack. pop()){
171
+ return false ;
172
+ }
173
+ }
174
+ // 4.返回
175
+ return stack. isEmpty();
176
+ }
177
+ }
178
+ ```
179
+
180
+ C++ Code:
181
+
182
+ ``` cpp
183
+ class Solution {
184
+ public:
185
+ bool isValid(string s) {
186
+ int n = s.size();
187
+ if (n % 2 == 1) {
188
+ return false;
189
+ }
190
+
191
+ unordered_map<char, char> pairs = {
192
+ {')', '('},
193
+ {']', '['},
194
+ {'}', '{'}
195
+ };
196
+ stack<char > stk;
197
+ for (char ch: s) {
198
+ if (pairs.count(ch)) {
199
+ if (stk.empty() || stk.top() != pairs[ch]) {
200
+ return false;
201
+ }
202
+ stk.pop();
203
+ }
204
+ else {
205
+ stk.push(ch);
206
+ }
207
+ }
208
+ return stk.empty();
209
+ }
210
+ };
211
+ ```
212
+
153
213
** 复杂度分析**
154
214
155
215
- 时间复杂度:$O(N)$
You can’t perform that action at this time.
0 commit comments