网友问题:
这是东北大学2004年硕士研究生考试的一道考题,15分,估计不是很复杂,但是就是没有思路,恨死我了。
设有算术表达式,其中包含有大括号“{ "" }" 中括号"[" "]" 小括号 "(" ")"
试编写一个递归函数,判断表达式中的括号是否匹配?
试编写一个递归函数,判断表达式中的括号是否匹配?
谢谢!
java程序,仅供参考:
package test;
import java.util.*;
public class Test {
public String text="fewe{f(sdd(f)a[j]sdk)j}f";
int i=0;
public LinkedList stack=new LinkedList();
public Test() {
}
public String analyiz(int ip){
char temp=text.charAt(ip);
char a;
if(temp=='('||temp=='['||temp=='{'){
stack.add(temp);
}else if(temp==')'){
a=(Character)stack.getLast();
if(a=='('){
stack.removeLast();
}
}else if(temp==']'){
a=(Character)stack.getLast();
if(a=='['){
stack.removeLast();
}
}else if(temp=='}'){
a=(Character)stack.getLast();
if(a=='{'){
stack.removeLast();
}
}
if(stack.size()==0&&ip==text.length()-1){
String c="匹配";
return c;
}else if(stack.size()!=0&&ip==text.length()-1){
String b="不匹配";
return b;
}else{
return analyiz(ip+1);//递归
}
}
public static void main(String[] args){
Test test=new Test();
String a=test.analyiz(0);
System.out.println(a);
}
}
int i=0;
public LinkedList stack=new LinkedList();
public Test() {
}
public String analyiz(int ip){
char temp=text.charAt(ip);
char a;
if(temp=='('||temp=='['||temp=='{'){
stack.add(temp);
}else if(temp==')'){
a=(Character)stack.getLast();
if(a=='('){
stack.removeLast();
}
}else if(temp==']'){
a=(Character)stack.getLast();
if(a=='['){
stack.removeLast();
}
}else if(temp=='}'){
a=(Character)stack.getLast();
if(a=='{'){
stack.removeLast();
}
}
if(stack.size()==0&&ip==text.length()-1){
String c="匹配";
return c;
}else if(stack.size()!=0&&ip==text.length()-1){
String b="不匹配";
return b;
}else{
return analyiz(ip+1);//递归
}
}
public static void main(String[] args){
Test test=new Test();
String a=test.analyiz(0);
System.out.println(a);
}
}
本文转自 xhinkerx 51CTO博客,原文链接:http://blog.51cto.com/xhinker/133585,如需转载请自行联系原作者