表达式有多种括号,包括[ ]、( )、{ }。本程序将检测用户输入的表达式是否合法,合法就输出YES,非法输出NO。
主要知识点:栈
㊣ StackX
/**
* 栈实现
* @author bbflyerwww
* @date 2006-08-10
*/
public class StackX {
private int maxSize;
private char[] stack;
private int top;
public StackX() {
maxSize = 1000;
stack = new char[maxSize];
top = -1;
}
public void push(char c) {
top++;
if (top >= maxSize)
System.out.println("StackX is full...");
else
stack[top] = c;
}
public char pop() {
char c;
if (top < 0) {
System.out.println("StackX is empty...");
c = 0;
} else
c = stack[top--];
return c;
}
public char peek() {
char c;
if (top < 0) {
System.out.println("StackX is empty...");
c = 0;
} else
c = stack[top];
return c;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize-1;
}
}
㊣ BacketChecker
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 括号匹配
* @author bbflyerwww
* @date 2006-08-10
*/
public class BacketChecker {
public static boolean check(String str) {
StackX sx = new StackX();
boolean flag = true;
int k = str.length();
for (int i = 0; i < k && flag; i++) {
char c = str.charAt(i);
if (c == '(' || c == '[' || c == '{')
sx.push(c);
else if (c == ')' || c == ']' || c == '}') {
char x = sx.pop();
switch (c) {
case ')':
if (x != '(') flag = false;
break;
case ']':
if (x != '[') flag = false;
break;
case '}':
if (x != '{') flag = false;
break;
default:
break;
}
} else {
;
}
}
if (!sx.isEmpty())
flag = false;
return flag;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println("/t/tBacket Matcher/t/t" +
"/n/t1 Input string like a[b(c)de]f{g}" +
"/n/t2 Q to Exit");
while (true) {
System.out.print("/tInput : ");
line = br.readLine();
if (line.equals("Q") || line.equals("q"))
break;
System.out.print("/tResult : ");
if (check(line))
System.out.println("YES");
else
System.out.println("NO");
}
}
}
㊣ 说明: java.util.Stack<E>类
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.
When a stack is first created, it contains no items.
Boolean empty()
E peek()
E pop()
E push(E item)
int search(Object o)