Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2756
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  被撕碎了的回忆
    2020-11-27 12:18

    If you want to have a look at my code. Just for reference

    public class Default {
    
        public static void main(String[] args) throws IOException {
    
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int numOfString = Integer.parseInt(br.readLine());
            String s;
            String stringBalanced = "YES";
            Stack exprStack = new Stack();
    
            while ((s = br.readLine()) != null) {
                stringBalanced = "YES";
                int length = s.length() - 1;
                for (int i = 0; i <= length; i++) {
                    char tmp = s.charAt(i);
    
                    if(tmp=='[' || tmp=='{' || tmp=='('){
                        exprStack.push(tmp);
                    }else if(tmp==']' || tmp=='}' || tmp==')'){
                        if(!exprStack.isEmpty()){
                            char peekElement = exprStack.peek();
                            exprStack.pop();
                            if(tmp==']' && peekElement!='['){
                                stringBalanced="NO";
                            }else if(tmp=='}' && peekElement!='{'){
                                stringBalanced="NO";
                            }else if(tmp==')' && peekElement!='('){
                                stringBalanced="NO";
                            }
                        }else{
                            stringBalanced="NO";
                            break;
                        }
                    }
    
                }
    
                if(!exprStack.isEmpty()){
                    stringBalanced = "NO";
                }
    
                exprStack.clear();
                System.out.println(stringBalanced);
            }
        }
    }
    

提交回复
热议问题