简体   繁体   English

Java中的括号检查器

[英]Parenthesis checker in java

I have made a parenthesis checker program in java that that reads in a text stream from standard input and uses a stack to determine whether or not its parentheses are properly balanced. 我在Java中制作了一个括号检查器程序,该程序从标准输入中读取文本流,并使用堆栈来确定其括号是否正确平衡。 For example, it should print true for [()]{}{[()()]()} and false for [(]) . 例如,它应该打印为真[()]{}{[()()]()}和假为[(]) I have made a stack class of my own for this problem: 我为这个问题做了一个自己的堆栈类:

public class Stack {
private char items[];
private int top;

Stack(int n){
    items = new char[n];
    top = -1; 
}

void push(char c){
    if(top == items.length-1){
        System.out.println("Stack full.");
        return;
    }
    top++;
    items[top] = c;
}

char pop(){
    if(isEmpty()){
        System.out.println("Stack empty");
        return (char)0;
    }
    char p;
    p = items[top];
    top--;
    return p;
}

boolean isEmpty(){
    if(top == -1)
        return true;
    else    
        return false;
}

} }

The checkValid method below takes a String input and returns true if the parentheses matches, and false if they do not match. 下面的checkValid方法接受String输入,如果括号匹配,则返回true;如果不匹配,则返回false。

    public static Boolean checkValid(String str){
        char sym,prev;
        Stack s = new Stack(str.length());
        for(int i=0; i<str.length();i++){
            sym = str.charAt(i);
            if(sym == '(' || sym=='{' || sym=='['){
                s.push(sym);
            }
            if(sym == ')' || sym=='}' || sym==']'){
               if(s.isEmpty()){
                   return false;
                }
               else{
                    prev = s.pop();
                    if(!isPairMatch(prev,sym))
                        return false;
               }
            }

        }
        if(!s.isEmpty())
            return false;
        return true;
    }
    public static boolean isPairMatch(char character1, char character2){
        if(character1 == '(' && character2 == ')')
            return true;
        else if(character1 == '{' && character2 == '}')
            return true;
        else if(character1 == '[' && character2 == ']')
            return true;
        else
            return false;
    }
}

Is there a way to print the position of the unmatched parentheses? 有没有办法打印不匹配括号的位置?

If your Stack, instead of holding chars , would hold a class that contains both the char and the index of that char in the input String, you'll be able to print the index of the unmatched parentheses. 如果你的筹码,而不是抱着chars ,将举行一个同时包含一类char和索引char的输入字符串,你就可以打印出括号不匹配的索引。

EDIT: 编辑:

This solution is only required if you want the indices of both unmatched parentheses that failed the isPairMatch test. 仅当您希望两个未匹配的括号的索引未通过isPairMatch测试时才需要此解决方案。

For example, if you have the String "[{}{}{})", the pair that doesn't match are the first "[" and last ")", whose indices are 0 and 7. 例如,如果您有字符串“ [{} {} {})”,则不匹配的对将是第一个“ [”和最后一个“)”,其索引分别为0和7。

If you only need the index of the first unmatched parenthesis (ie the first "[" whose index is 0), you simply check the size of the Stack after the removal of that parenthesis. 如果只需要第一个不匹配括号的索引(即索引为0的第一个“ [”),则只需在删除括号后检查堆栈的大小即可。 In this example, the stack would be empty when the last pair is checked, so the size of the stack would be 0, which is the index of the first char of the failed isPairMatch test. 在此示例中,当检查最后一对时,堆栈将为空,因此堆栈的大小将为0,这是失败的isPairMatch测试的第一个char的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM