栈应用 , 判断表达式是否正确

来源:互联网 发布:python requests post 编辑:程序博客网 时间:2024/06/03 03:57

一,模拟栈

     

package com.zf.test;public class StackX {private int maxLengh ;private int top ;private Character[] array ;public StackX(int maxLengh){this.maxLengh = maxLengh ;this.array = new Character[maxLengh];this.top = -1 ;}public int size(){return this.top ;}public void put(char entry){if(isFull())throw new ArrayIndexOutOfBoundsException("array is fully!");array[++top] = entry ;}    public char pop(){if(isEmpty())  throw new ArrayIndexOutOfBoundsException("array is empty!");return array[top--];}public boolean isEmpty(){return top == -1 ;}public boolean isFull(){return top == maxLengh - 1;}}


 

 

2,应用

 

package com.zf.test;public class ExpressionMatcher {private final static int right = 0 ;private final static int left = 1 ; public static boolean matcher(String expStr){StackX sx = new StackX(100);for (int i = 0; i < expStr.length(); i++) {  char c = expStr.charAt(i);if(obtainFh(c) == left){sx.put(c);}else if(obtainFh(c) == right){if(sx.isEmpty())throw new RuntimeException("没找到匹配项:" + c);char l = sx.pop(); if(!matchers(l, c)){ throw new RuntimeException(l  + " 与 " + c + "不匹配");}}}return sx.isEmpty();}private static int obtainFh(char c){switch(c){case '(' : case '[' :case '{' :return left ;case ')' :case ']' :case '}' :return right ;default : return -1 ; }}    private static boolean matchers(char left , char right){if((left == '(' && right == ')')|| (left == '[' && right == ']')|| (left == '{' && right == '}')   ) return true ;return false;}    public static void main(String[] args) {System.out.println(matcher( "212(1(21)1){4(5)4{5}}") );}}


 

原创粉丝点击