测试用例:"(()())",6
返回:true
测试用例:"()a()()",7
返回:false
测试用例:"()(()()",7
返回:false
思路:1.碰到")“开始弹出栈顶的”(",如果此时栈为空,则返回false
2.碰到其他内容直接返回false
3.字符串结尾时,栈非空返回false
public class Main2 {
public static boolean chkParenthesis(String string, int n){
Stack<Character> stack = new Stack<>();
if (string.length() != n || string == null){
return false;
}
for (int i = 0; i < n; i++) {
if (string.charAt(i) == '('){
stack.push(string.charAt(i));
}else if (string.charAt(i) == ')'){
if (stack.empty()){
return false;
}else {
stack.pop();
}
}else {
//这一步是检查是否包含其他元素 比如 字符 数字
return false;
}
}
if (!stack.empty()){
return false;
}else {
return true;
}
}
}