给定一个字符串A和其长度n,请返回一个bool值代表它是否为一个合法的括号串(只能由括号组成)。
测试样例:
"(()())",6
返回:true
测试样例:
"()a()()",7
返回:false
测试样例:
"()(()()",7
返回:false
import java.util.*;
public class Parenthesis {
public static void main(String[] args) {
// Stack<String> stack = new Stack<>();
Scanner sc = new Scanner(System.in);
String A = sc.nextLine();
int n = A.length();
System.out.println(chkParenthesis(A, n));
}
public static boolean chkParenthesis(String A, int n) {
// write code here
Stack<Character> stack = new Stack<>();
char[] chars = A.toCharArray();
for (char ch : chars) {
if (ch == '(' ) {
stack.push(ch);//将数组中所有左括号全部放入栈中
} else {
//如果不满足放栈条件,说明是右括号,判断栈是否是空栈,空为没有左括号
if (stack.isEmpty()) {
return false;
}
char left = stack.pop();//取出栈顶元素进行配对,配对不成功返回false;
if (left == '(' && ch == ')') {
} else {
return false;
}
}
}
return stack.isEmpty();
}
}