做一个空栈,读入字符直到结尾.如果读入一个封闭符号,空栈时报错;非空时弹出栈尾字符,如果不匹配则报错.否则读入为开放字符,压入栈中.最后如果栈空,返回true.
其中用到MyStack类,详情请见
1 public class KuohaoJiancha { 2 private char [] item = {‘(‘,‘)‘,‘[‘,‘]‘,‘{‘,‘}‘}; 3 private MyStack stack = new MyStack(); 4 private char[] str; 5 private int currentNum; 6 public KuohaoJiancha(String str){ 7 this.str = str.toCharArray();; 8 } 9 10 public boolean display(){ 11 for(int i = 0; i < str.length; i++){ 12 currentNum = charNumber(str[i]); 13 if(misByStackIsEmpty(str[i])) 14 return false; 15 16 if(currentNum % 2 == 1) { 17 if (currentNum - charNumber((char) stack.pop()) != 1) 18 return false; 19 } 20 else stack.push(str[i]); 21 } 22 return true; 23 } 24 25 private int charNumber(char c){ 26 int i = 0; 27 for(; i < 6; i++){ 28 if(c == item[i]) 29 break; 30 } 31 return i; 32 } 33 34 private boolean misByStackIsEmpty(char c){//如果读入一个封闭符号,空栈时报错 35 if(stack.isEmpty()) 36 if(currentNum % 2 == 1) 37 return true; 38 return false; 39 } 40 41 }
时间: 2024-10-08 23:47:20