题解 | #合法括号序列判断#
合法括号序列判断
https://www.nowcoder.com/practice/d8acfa0619814b2d98f12c071aef20d4
import java.util.*;
public class Parenthesis {
public boolean chkParenthesis(String A, int n) {
// write code here
if(n % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
for(char ch : A.toCharArray()) {
if(ch == '(') {
stack.push(ch);
} else if(ch == ')') {
if(stack.isEmpty()) {
return false;
} else if(stack.peek() == '(') {
stack.pop();
}
} else {
return false;
}
}
return stack.isEmpty();
}
}

