分隔符包括“{“、"["、”(”、“] “、“)“、“}”,每个左分隔符需要右分隔符匹配。同时,在字符串中后出现左分隔符应该比早出现的先匹配。
程序从字符串中不断读取字符,每次读取一个字符。若发现是左分隔符,压入栈中;当读到一个右分隔符,弹出栈的左分割符与其比较,如果不匹配则报错。
栈中没有左分隔符和右分隔符匹配/一直存在着没有被匹配的分隔符,报错。
//栈
package StructureBracket;
public class StackX {
private int maxSize;
private char[] stackArray;
private int top;
//构造器
public StackX(int s){
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j){
stackArray[++top] = j;
}
public char pop(){
return stackArray[top--];
}
public char peek(){
return stackArray[top];
}
public boolean isEmpty(){
return(top == -1);
}
}
//匹配程序
package StructureBracket;
public class BracketChecker {
private String input;
public BracketChecker(String in){
input = in;
}
public void check(){
int stackSize = input.length();
StackX theStack = new StackX(stackSize);
for(int j=0;j
char ch = input.charAt(j);
switch(ch){
case '{':
case '[':
case '(':
theStack.push(ch);
break;
case '}':
case ']':
case ')':
if(!theStack.isEmpty()){
char chx = theStack.pop();
if((ch=='}')&&(chx!='{')||(ch==']')&&(chx!='[')
||(ch==')')&&(chx!='('))
System.out.println("Error: "+ch+" at "+j);
}else
System.out.println("Error: "+ch+" at "+j);
break;
default:
break;
}//end switch
}//end for
if(!theStack.isEmpty())//若能执行到此步,说明以上只执行了push
System.out.println("Error:missing right delimiter");
}
}
//主程序
package StructureBracket;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class BracketsApp {
public static void main(String[] args)throws IOException{
String input;
while(true){
System.out.print("Enter string containing delimiters: ");
System.out.flush();
input = getString();
if(input.equals(""))
break;
BracketChecker theChecker = new BracketChecker(input);
theChecker.check();
}
}
private static String getString() throws IOException {
// TODO Auto-generated method stub
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
}
转换规则:
(1)遇到操作数:直接写至输出out;
(2)左括号(:push入栈;(3):右括号):pop出一项,若此项不是(则写至out,若是(则退出循环;
(3)若读到操作符(+、-、*、/等):栈为空,push推其入栈;栈非空,重复:pop一项,若为(push其入 栈,若同样为操作符,比较其优先级:>栈顶push其入栈,≤栈顶,输出栈顶操作符,<栈顶退出循环;项为(,将读到的操作符push入栈;
(4):以上步骤结束后,若栈非空,弹出写至输出out.