import java.util.*; public class Parenthesis { public boolean chkParenthesis(String A, int n) { /** //方法一。用count来计数 if(n % 2 == 1) { return false; } int count = 0; for(int i = 0; i < n; i++){ if (A.charAt(i) == '(') { count++; } else if(A.charAt(i) == ')') { if(count < 0) { return false; } count--; } else { count = -1; break; } } if(count == 0) { return true; } else { return false; } */ //方法二:用栈来储存 if(n % 2 == 1) { 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(); } }