括号匹配算法java



这是我实现的括号匹配算法。然而,有人能告诉我出了什么问题吗。我一直都是真的,例如输入:{}(

public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
for(int i= 0; i<stack.size();i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{')  ||                      (current == ')' && top == '(')){
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty){
return true;
}else{
return false;
}
}

您使用的是stack的大小作为绑定,而不是stringToCheck的大小。堆栈在之前刚刚初始化,因此您的循环将被跳过。

您的程序是正确的,除了下面代码中提到的注释

public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
int n = stringToCheck.length; // take the length of the given char array
for(int i= 0; i < n;i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{')  ||                      (current == ')' && top == '(')){
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty()){ // function call of stack isEmpty()
return true;
}else{
return false;
}
}

对循环使用字符串ToCheck长度,而不是堆栈大小。然后,stack.isEmptyisEmpty是一个方法,您忘记了括号。

public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
for(int i= 0; i<stringToCheck.length();i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{')  || (current == ')' && top == '(')) {
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty()){
return true;
}else{
return false;
}
}

最新更新