2025-05-17提交

This commit is contained in:
asahi
2025-05-17 17:01:56 +08:00
parent c4e1e74677
commit a62543b3fd
7 changed files with 454 additions and 0 deletions

78
20.valid-parentheses.java Normal file
View File

@@ -0,0 +1,78 @@
/*
* @lc app=leetcode id=20 lang=java
*
* [20] Valid Parentheses
*/
// @lc code=start
import java.util.Deque;
class Solution {
public boolean isValid(String s) {
int br_1_cnt = 0, br_2_cnt = 0, br_3_cnt = 0;
Deque<Integer> op_type_stack = new ArrayDeque<Integer>();
for(int i=0;i<s.length();i++) {
char ch = s.charAt(i);
if(isOpenBr(ch)) {
int op_type = getOpenBrType(ch);
op_type_stack.push(op_type);
if(op_type == 1) {
br_1_cnt++;
} else if(op_type == 2) {
br_2_cnt++;
} else if(op_type == 3) {
br_3_cnt++;
}
} else {
int close_type = getCloseBrType(ch);
if(op_type_stack.isEmpty()) {
return false;
} else if(op_type_stack.peek() != close_type) {
return false;
}
op_type_stack.pop();
if(close_type == 1) {
br_1_cnt--;
} else if(close_type == 2) {
br_2_cnt--;
} else if(close_type == 3) {
br_3_cnt--;
}
}
}
return br_1_cnt == 0 && br_2_cnt == 0 && br_3_cnt == 0;
}
private boolean isOpenBr(char ch) {
return ch == '(' || ch == '[' || ch == '{';
}
private int getOpenBrType(char ch) {
switch(ch) {
case '(':
return 1;
case '[':
return 2;
case '{':
return 3;
default:
throw new RuntimeException("invalid open brack");
}
}
private int getCloseBrType(char ch) {
switch(ch) {
case ')':
return 1;
case ']':
return 2;
case '}':
return 3;
default:
throw new RuntimeException("invalid close brack");
}
}
}
// @lc code=end