解题思路:
本题用栈来写, 遍历数组,比较
1.为左括号入栈
2.右括号时,先判断栈是否为空,如果不为空删除栈顶元素,如果为空,直接返回false
3.遍历完成后,看栈是否为空,如果为空,返回true,否则false(多了一些左括号)
例:输入(()())6 输出: true
import java.util.*;
public class Parenthesis {
public boolean chkParenthesis(String A, int n) {
// write code here
Stack stack=new Stack();
for(int i=0;i<n;i++){
if(A.charAt(i)=='('){
stack.push(A.charAt(i));
}
if(A.charAt(i)==')'){
if(!stack.isEmpty()){
stack.pop();
}else {
return false;
}
}
}
if(stack.isEmpty()){
return true;
}
return false;
}
}