前段时间在面试的过程中被问到如何判断括号的配对问题。当时只说了大致的思路,今天闲下来实现一下
package dataStructure;
import java.util.Scanner;
public class IsMatch {
static boolean isMatch(LLStack stack) {
System.out.println("请输入表达式:");
Scanner scanner = new Scanner(System.in);
String curString = scanner.next();
//字符处理
for(int i = 0; i < curString.length(); i++) {
char ch = curString.charAt(i);
switch(ch) {
case '(' :
stack.push(ch);
break;
case '[' :
stack.push(ch);
break;
case '{' :
stack.push(ch);
break;
case ')' :
if(stack.isEmpty() || stack.top() != '(' ) {
System.out.println("匹配失败");
return false;
}else {
stack.pop();
}
break;
case ']' :
if(stack.isEmpty() || stack.top() != '[' ) {
System.out.println("匹配失败");
return false;
}else {
stack.pop();
}
break;
case '}' :
if(stack.isEmpty() || stack.top() != '{' ) {
System.out.println("匹配失败");
return false;
}else {
stack.pop();
}
break;
}
}
//字符处理后栈非空
if(!stack.isEmpty()) {
System.out.println("匹配失败");
return false;
}
System.out.println("匹配成功");
return true;
}
public static void main(String[] args) {
LLStack stack = new LLStack();
while(isMatch(stack)) {
}
}
}
使用java来实现栈
class LLNode{
private char data;
private LLNode next = null;
public LLNode(char d){
data = d;
}
public char getData() {
return data;
}
public void setData(char data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
}
public class LLStack {
private LLNode head;
boolean isEmpty() {
return head == null;
}
int size() {
int count = 1;
LLNode cur = head;
if(isEmpty()) return 0;
while(cur.getNext() !=null ) {
cur = cur.getNext();
count++;
}
return count;
}
char top() {
if(isEmpty())
return 0;
return head.getData();
}
void push(char d) {
if(isEmpty()) {
head =new LLNode(d);
}else {
LLNode node = new LLNode(d);
node.setNext(head);
head = node;
}
}
char pop() {
if(isEmpty())
new Exception("栈空");
LLNode del = head;
head = head.getNext();
return del.getData();
}
void display() {
if(isEmpty()) {
System.out.println("栈空");
}else {
LLNode cur = head;
System.out.print("栈内元素:");
while(cur != null) {
System.out.print(cur.getData() + "->");
cur = cur.getNext();
}
System.out.println();
}
}
void deleteStack() {
head = null;
}